Java开发Web Service客户端技巧:wsimport、jaxws-maven-plugin、整合Spring
搭建一个简单的Web Service服务器
要想跑Web Service客户端,前提是要有个Web Service服务器。如果你已经有Web Service服务器,那么可以跳过这一步。如果没有,可以使用JAX-WS搭建一个简单的Web Service服务器。
1  | @WebService  | 
直接启动程序运行main方法,即完成搭建了一个简单的Web Service服务器了。可以通过地址http://127.0.0.1:8096/helloWorld?wsdl查看Web Service的WSDL。WSDL是用来告诉我们如何去调用这个Web Service。
wsimport命令
在JDK的安装目录的bin目录下,有一个wsimport.exe文件,如果是Linux系统也可以找到相应的wsimport文件。在配置好环境变量的情况下,可以使用wsimport命令生成Web Service客户端的Java代码。
1  | wsimport -s D:\xxg -Xnocompile -p com.xxg.wsclient http://127.0.0.1:8096/helloWorld?wsdl  | 
参数介绍:-s 指定Java文件的生成目录-p 指定Java的package-Xnocompile 不需要编译成class文件
命令执行完成后,在目标文件夹下会生成Web Service客户端Java代码:
使用生成的Java客户端:1
2
3
4public static void main(String[] args) throws MalformedURLException {
    HelloWorld helloWorld = new HelloWorldService(new URL("http://127.0.0.1:8096/helloWorld?wsdl")).getHelloWorldPort();
    System.out.println(helloWorld.sayHello("xxg")); // 输出"Hello xxg"
}
以上程序即是一个简单的Web Service客户端,它会调用Web Service并输出返回结果。
jaxws-maven-plugin插件
以上客户端代码是通过wsimport命令生成,也可以通过Maven插件
jaxws-maven-plugin来生成Web Service客户端Java代码。在pom.xml中配置插件:
1  | <plugin>  | 
新版本的jaxws-maven-plugin插件groupId是org.jvnet.jax-ws-commons,而老版本的groupId是org.codehaus.mojo,这里选用的是目前最新版本2.3。
配置好插件后,运行Maven指令:1
mvn jaxws:wsimport
也可以很方便的生成Web Service客户端Java代码。
整合Spring框架
Spring框架提供了对Web Service客户端良好的支持,可以通过Spring来配置和管理Web Service客户端。
1  | <bean id="webservice" class="org.springframework.remoting.jaxws.JaxWsPortProxyFactoryBean">  | 
以上配置项中,serviceInterface指定生成的代码中对应的Class,wsdlDocumentUrl执行WSDL路径,namespaceUri、serviceName、portName都可以在WSDL文件中找到。org.springframework.remoting.jaxws.JaxWsPortProxyFactoryBean需要依赖包spring-web.jar。
运行下面对Spring管理的Web Service客户端进行测试:1
2
3
4
5public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    HelloWorld helloWorld = context.getBean("webservice", HelloWorld.class);
    System.out.println(helloWorld.sayHello("xxg")); // 输出"Hello xxg"
}

