项目框架中要增加webservice的功能,引入了cxf2.7.6作为框架支持,为了加快客户端的编写,采用生成的方式通过wsdl生成客户端代码。
客户端代码自自动生成有三种方式:
The WSDL2Java tool will generate JAX-WS clients from your WSDL. You can run WSDL2java one of three ways:
The command line
The Maven Plugin
With the WSDL2Java API
第一种通过wsdl2java命令行的形式测试通过,但通过java调用外部命令总是有环境变量的问题还要配置相应工具路径等操作,比较麻烦。
第二种通过Maven Plugin生成,对Maven不熟悉,跳过
第三种通过WSDL2Java API生成,在网上百度谷歌的搜索了半天,没有这样的文章,也没有这么做的,可能是方法太过偏激了。但为了框架中可以保证开发人员对webservice的使用可以快速上手,便花了很长时间研究这个事儿,后来在wsdl2java.bat中找到解决办法。
解决办法如下:
1. 工具类:
import java.net.URLDecoder;
import java.util.Locale;
import java.util.ResourceBundle;
import org.apache.cxf.tools.common.ToolContext;
import org.apache.cxf.tools.wsdlto.WSDLToJava;
/**
* @desc 客户端代码生成工具类
* @version v1.0, 2013-12-11
*/
public class ClientCodeGenerator {
public static void main(String[] args) throws Exception {
ClientCodeGenerator.generateClient();
}
public static void generateClient() {
try {
System.out.println("---------------client code generate starting.--------------");
String properties = "com.apps.mymis.demo.webservice.client.wsdl2java.ws-client-config";
ResourceBundle rb = ResourceBundle.getBundle(properties, Locale.getDefault());
String serviceWsdlUrl = rb.getString("ws.client.serviceWSDLUrl");
String stubcodeTargetPath = rb.getString("ws.client.stubCodeTargetPath");
String async = rb.getString("ws.client.async");
System.out.println("---------------service WSDL URL is " + serviceWsdlUrl + ".--------------");
System.out.println("---------------client code save at " + stubcodeTargetPath + ".--------------");
WSDLToJava w2j = null;
String bindingPath = URLDecoder.decode(ClientCodeGenerator.class.getResource("").getPath()).substring(1) + "anyc_binding.xml";
System.out.println(bindingPath);
if ("true".equals(async))
w2j = new WSDLToJava(new String[] { "-client", "-d", stubcodeTargetPath, "-b", bindingPath,
serviceWsdlUrl });
else
w2j = new WSDLToJava(new String[] { "-client", "-d", stubcodeTargetPath, serviceWsdlUrl });
w2j.run(new ToolContext());
System.out.println("---------------client code generate finished.--------------");
} catch (Exception e) {
e.printStackTrace();
}
}
}
2. 配置文件 ws-client-config.properties
#服务端wsdl文件本地路径或者wsdl地址
ws.client.serviceWSDLUrl=http://127.0.0.1:8080/test/service/TestAyncService?wsdl
#客户端代码需要存储的位置
ws.client.stubCodeTargetPath=c\:
#是否生成异步代码
ws.client.async=false
3. anyc_binding.xml 用于生成异步客户端代码的配置文件(可无视,与此主题无关)
<bindings xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
wsdlLocation="http://127.0.0.1:8080/test/service/TestAyncService?wsdl"
xmlns="http://java.sun.com/xml/ns/jaxws">
<bindings node="wsdl:definitions">
<enableAsyncMapping>true</enableAsyncMapping>
</bindings>
</bindings>
执行java工具类即可生成客户端代码。
PS:org.apache.cxf.tools.wsdlto.WSDLToJava类的参数与wsdl2java命令的参数格式相同
本文介绍了一种通过Apache CXF的WSDLToJava工具自动生成WebService客户端代码的方法。该方法利用Java API避免了环境变量配置等问题,并提供了一个实用的工具类及配置文件示例。

1万+

被折叠的 条评论
为什么被折叠?



