Java 17+Apache CXF 3.5.0构建SOAP客户端遇Marshalling Error求助
解决CXF SOAP客户端Marshalling Error问题
针对你遇到的https.www_w3schools_com.xml.CelsiusToFahrenheit is not known to this context错误,以下是具体修复步骤:
1. 确保JAXB上下文正确包含生成的类
CXF的SOAP客户端依赖JAXB完成对象与XML的转换,若请求类未被注册到JAXB上下文就会触发该错误:
- 显式指定JAXB上下文的包路径:
TempConvert service = new TempConvert(); // 初始化JAXB绑定,指定生成类所在的包 JAXBDataBinding binding = new JAXBDataBinding("https.www_w3schools_com.xml"); service.setDataBinding(binding); TempConvertSoap port = service.getTempConvertSoap(); // 调用服务方法 String result = port.celsiusToFahrenheit("25"); - 检查生成代码中是否存在
ObjectFactory.java和package-info.java,这两个类是JAXB识别类的核心,若缺失需重新生成代码。
2. 适配Java 17的Maven依赖配置
Java 9+移除了JDK自带的JAXB模块,需手动添加相关依赖,同时确保CXF 3.5.0与Java 17兼容:
<dependencies> <!-- CXF核心SOAP依赖 --> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-frontend-jaxws</artifactId> <version>3.5.0</version> </dependency> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-rt-transports-http</artifactId> <version>3.5.0</version> </dependency> <!-- JAXB依赖,适配Java 17 --> <dependency> <groupId>javax.xml.bind</groupId> <artifactId>jaxb-api</artifactId> <version>2.3.1</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-core</artifactId> <version>2.3.7</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> <version>2.3.7</version> <scope>runtime</scope> </dependency> </dependencies>
3. 重新生成规范的客户端代码
默认生成的包名(https.www_w3schools_com.xml)容易出现上下文识别问题,建议通过Maven插件指定清晰的包名重新生成:
<build> <plugins> <!-- CXF代码生成插件 --> <plugin> <groupId>org.apache.cxf</groupId> <artifactId>cxf-codegen-plugin</artifactId> <version>3.5.0</version> <executions> <execution> <id>generate-soap-client</id> <phase>generate-sources</phase> <configuration> <wsdlOptions> <wsdlOption> <wsdl>https://www.w3schools.com/xml/tempconvert.asmx?WSDL</wsdl> <!-- 指定自定义包名,避免默认的复杂路径 --> <packageName>com.w3schools.tempconvert</packageName> </wsdlOption> </wsdlOptions> </configuration> <goals> <goal>wsdl2java</goal> </goals> </execution> </executions> </plugin> <!-- Java 17编译配置 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.10.1</version> <configuration> <source>17</source> <target>17</target> </configuration> </plugin> </plugins> </build>
执行mvn generate-sources生成代码后,使用新包下的类编写客户端,示例代码:
package com.w3schools.tempconvert; public class TempConvertClient { public static void main(String[] args) { TempConvert service = new TempConvert(); TempConvertSoap port = service.getTempConvertSoap(); // 调用温度转换方法 String fahrenheit = port.celsiusToFahrenheit("0"); System.out.println("0℃ = " + fahrenheit + "℉"); } }
4. 模块化项目额外配置
如果你的项目是Java模块化项目(存在module-info.java),需添加模块依赖:
module your.module.name { requires org.apache.cxf.jaxws; requires javax.xml.bind; // 开放生成类的包给JAXB opens com.w3schools.tempconvert to com.sun.xml.bind; }
内容的提问来源于stack exchange,提问作者Daniel Falcão
相关产品推荐
相关产品推荐

