Apache CXF 客户端开发

通过 WSDL 生成 Java 代码

在 IDEA 配置 CXF Engine 时各种不让我选择目录,不知道什么原因,因此通过命令行来生成:

1
${apache-cxf-home}/bin/wsdl2java -encoding utf-8 -d ${output-dir} -p ${package-name} -client ${wsdl-url}
  • apache-cxf-home: CXF 目录
  • output-dir: 生成的代码输出目录
  • package-name: 生成的 Java 代码的包路径
  • wsdl-url: 远端的调用地址( ?wsdl )

添加 Maven 依赖

<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-frontend-jaxws</artifactId>
    <version>3.1.6</version>
</dependency>
<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-transports-http</artifactId>
    <version>3.1.6</version>
</dependency>

Java Config 方式与 Spring 整合

网上包括官方文档都比较老,单独写个实例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* @author sunshow
*/
@Configuration
public class CxfConfig {
@SuppressWarnings("unchecked")
private <T> T createJaxWsClient(Class<T> serviceClass, String address) {
JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
jaxWsProxyFactoryBean.setServiceClass(serviceClass);
jaxWsProxyFactoryBean.setAddress(address);
jaxWsProxyFactoryBean.getInInterceptors().add(new LoggingInInterceptor());
jaxWsProxyFactoryBean.getOutInterceptors().add(new LoggingOutInterceptor());
T service = (T) jaxWsProxyFactoryBean.create();
Client client = ClientProxy.getClient(service);
if (client != null) {
HTTPConduit conduit = (HTTPConduit) client.getConduit();
HTTPClientPolicy policy = new HTTPClientPolicy();
policy.setConnectionTimeout(30000);
policy.setReceiveTimeout(30000);
conduit.setClient(policy);
}
return service;
}
@Bean
public ServiceAPI serviceAPI() {
return createJaxWsClient(ServiceAPI.class, "https://xxx/services/queryService");
}
}