背景
使用Apache CXF生成客户端代码有两种方式
方式一
在官网http://cxf.apache.org下载Apache CXF后,cmd进入目录apache-cxf-3.2.13\bin, 输入命令
wsdl2java http://localhost:8888/HelloService?wsdl
即可生成客户端代码。
方式二
如果你希望将客户端打成jar包,可以用CXF的maven plugin。IDEA为例打包步骤如下:
1. 新建maven工程,引入plugin依赖
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.7.2</version>
<configuration>
<forkMode>once</forkMode>
<argLine>-Dfile.encoding=UTF-8</argLine>
<systemProperties>
<property>
<name>net.sourceforge.cobertura.datafile</name>
<value>target/cobertura/cobertura.ser</value>
</property>
</systemProperties>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-codegen-plugin</artifactId>
<version>3.2.13</version>
<executions>
<execution>
<id>generate-sources</id>
<phase>generate-sources</phase>
<configuration>
<sourceRoot>${project.basedir}/src/main/java</sourceRoot>
<encoding>UTF-8</encoding>
<wsdlOptions>
<!-- 指定wsdl文件 -->
<wsdlOption>
<wsdl>http://localhost:8888/HelloService?wsdl</wsdl>
</wsdlOption>
<!-- <wsdlOption>-->
<!-- <wsdl>${basedir}/src/main/resources/ccCoding.wsdl</wsdl>-->
<!-- </wsdlOption>-->
</wsdlOptions>
</configuration>
<goals>
<goal>wsdl2java</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
2. 直接点击maven install,即可生成客户端jar包
客户端调用方式
public static void main(String[] args) throws Exception {
URL url = new URL("http://localhost:8888/HelloService?wsdl");
QName qName = new QName("http://service.example.com/", "HelloServiceImplService");
HelloServiceImplService service = new HelloServiceImplService(url, qName);
HelloService helloService = service.getPort(HelloService.class);
String result = helloService.sayHelloMethod("Rocky", 25);
System.out.println(result);
}