cxf-rt-frontend-jaxws、cxf-rt-transports-httpspring-web、spring-context<servlet>
<servlet-name>cxf</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<init-param>
<param-name>config-location</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>cxf</servlet-name>
<url-pattern>/webservice/*</url-pattern>
</servlet-mapping>
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxws="https://cxf.apache.org/jaxws"
xsi:schemaLocation="
https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
https://cxf.apache.org/jaxws https://cxf.apache.org/schemas/jaxws.xsd">
<!-- 服務實現 Bean -->
<bean id="helloService" class="com.example.HelloServiceImpl"/>
<!-- 發布端點 -->
<jaxws:endpoint id="helloEndpoint"
implementor="#helloService"
address="/hello" />
</beans>
@WebService
public interface HelloService {
String sayHello(String name, int age);
}
@WebService(endpointInterface = "com.example.HelloService")
public class HelloServiceImpl implements HelloService {
public String sayHello(String name, int age) {
return "Hello " + name + ", age: " + age;
}
}
啟動項目後訪問:https://localhost:8080/webservice/hello?wsdl 獲取 WSDL 文檔
# 命令行生成客戶端存根
wsdl2java -d src/main/java -client https://localhost:8080/webservice/hello?wsdl
生成的代碼包含:服務接口、Service 工廠類、異常類等。直接 new Service 獲取 Port 調用。
<beans xmlns:jaxws="https://cxf.apache.org/jaxws" ...>
<jaxws:client id="helloClient"
serviceClass="com.example.HelloService"
address="https://localhost:8080/webservice/hello" />
</beans>
public class ClientTest {
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext("client-context.xml");
HelloService proxy = ctx.getBean("helloClient", HelloService.class);
System.out.println(proxy.sayHello("測試", 25));
}
}
<jaxws:client> 子元素 <jaxws:properties> 設置 connectionTimeout/receiveTimeoutcxf-rt-ws-security,配置 WSS4JInInterceptor/OutInterceptor<cxf:bus> 掛載 LoggingInInterceptor/LoggingOutInterceptor@MTOM 註解,客戶端啟用 mtom-enabled="true"| 現象 | 原因 | 解決 |
|---|---|---|
| 404 Not Found | url-pattern / address 不匹配 | 檢查 /webservice/* + address="/hello" → 完整路徑 /webservice/hello |
| ClassCastException | 客戶端/服務端模型類版本不一致 | 共享模型 JAR 或強制同步 serialVersionUID |
| 命名空間不匹配 | WSDL targetNamespace 與代碼不符 | @WebService(targetNamespace="...") 顯式指定 |