由于项目需要兼容旧系统,要使用webservice,好久没用WebService了,特别是springboot时代,REST当道,WebService资料仅限于SpringFramework。于是研究了一下springboot中使用CXF.
使用的关键问题是,webservice的URL必须要动态配置。
第一步是要编译wsdl, 需要在pom.xml看引入cxf-plugin:
<plugin>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-codegen-plugin</artifactId>
<version>${cxf.version}</version>
<executions>
<execution>
<id>generate-sources</id>
<phase>generate-sources</phase>
<configuration>
<sourceRoot>${project.build.directory}/generated-sources/cxf</sourceRoot>
<wsdlOptions>
<wsdlOption>
<wsdl>${basedir}/src/main/resources/wsdl/*.wsdl</wsdl>
</wsdlOption>
</wsdlOptions>
</configuration>
<goals>
<goal>wsdl2java</goal>
</goals>
</execution>
</executions>
</plugin>
这样cxf就能自动把wsdl目录下所有wsdl文件编译成java代码。其中,有一个XxxServiceLocal的接口,就是我们要调用的远程服务接口。
第二步,创建XxxServiceLocal实例
这一步是关键,wsdlUrl要能动态配置的。以前是用spring-beans.xml中声明,如:
<jaxws:client id="XXXService" serviceClass="com.abc.service.XXXServicePortType" address="${app.xxx.service.wsdl.url}" >
</jaxws:client>
现在要用Springboot @Configuration 对象工厂了:
@Configuration
public class XXXServiceConfig {
@Value("${app.xxx.service.wsdl.url}")
private String wsdlUrl;
XXXServiceLocal getXXXService() {
XXXService service = new XXXService(new URL(wsdlUrl));
return service.getXXXServiceBeanPort();
}
}
然后,你就可以简单的注入和使用远程服务了。
@Autowired
XXXServiceLocal xxxService;