这里使用的Maven,Java 8来操作的。
Maven相关代码为:
org.springframework.boot
spring-boot-starter-web
org.projectlombok
lombok
true
org.springframework.boot
spring-boot-starter-test
test
wsdl4j
wsdl4j
1.6.1
org.springframework.ws
spring-ws-core
3.0.8.RELEASE
buid里面要添加一个插件:
org.springframework.boot
spring-boot-maven-plugin
org.codehaus.mojo
jaxb2-maven-plugin
2.5.0
xjc
xjc
${project.basedir}/src/main/resources/countries.xsd
这里要创建一个xml,通过这个xml生成对应的Object
这里countries.xsd为:
其中target/jaxb/com/it1995/example/demo是这样生成的:
其中这个文件路径是xsd文件xmlns:tns,targetNamespace
xmlns:tns和targetNamespace生成对应的包。
下面是关于各个文件的分析:
CountryRepository.java:存储城市的数据,为webService提供数据。
CountryEndpoint.java:创建服务端,需要使用到POJO类及少量的Spring WS注解处理SOAP的请求。
其中:
其中NAMESPACE_URL为XML里面的xmlns:tns,targetNamespace。其中里面涉及几个注解:
@Endpoint:将此类注册为Spring WS的候选类,用于接收SOAP消息;
@PayloadRoot:这个也是Spring WS的注解作用在方法上其中namespace填写xml的namespace,而localpart填写xml中作用的方法;
@RequestPayload:方法中参数的注解,将SOAP传过来的数据映射到参数中;
@ResponsePayload:返回响应数据。
WebServiceConfig.java:配置Spring WS相关的配置Bean
@EnableWs
@Configuration
public class WebServiceConfig extends WsConfigurerAdapter {
@Bean
public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean(servlet, "/ws/*");
}
@Bean(name = "countries")
public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema countriesSchema) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName("CountriesPort");
wsdl11Definition.setLocationUri("/ws");
wsdl11Definition.setTargetNamespace("http://it1995.com/example/demo");
wsdl11Definition.setSchema(countriesSchema);
return wsdl11Definition;
}
@Bean
public XsdSchema countriesSchema() {
return new SimpleXsdSchema(new ClassPathResource("countries.xsd"));
}
}
Spring WS有自己的servlet用于处理SOAP消息。上面的MessageDispatcherServlet十分重要,他将ApplicatoinContext注入到了MessageDispatcherServlet。并且这个Bean并不会影响Spring 的默认Bean。
程序运行截图如下:
源码打包下载地址:
https://github.com/fengfanchen/Java/tree/master/SOAPWebProduction