SOAP 1.2 协议实战:Spring Boot 3.x 构建国家查询服务(附完整代码)
在当今企业级应用集成领域,SOAP协议依然是金融、电信等关键行业的数据交换标准。本文将带您使用Spring Boot 3.x实现一个符合SOAP 1.2规范的国家信息查询服务,涵盖从WSDL定义到异常处理的完整开发流程。
1. 环境准备与项目初始化
首先创建一个基础的Spring Boot项目,添加必要的依赖:
<dependencies>
<!-- Spring Boot Starter for Web Services -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
</dependency>
<!-- XML Binding (JAXB) -->
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
</dependency>
<!-- XJC工具链 -->
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
配置Maven插件用于XSD到Java类的生成:
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<id>xjc</id>
<goals><goal>xjc</goal></goals>
</execution>
</executions>
<configuration>
<sources>
<source>src/main/resources/schemas/countries.xsd</source>
</sources>
</configuration>
</plugin>
</plugins>
</build>
2. 定义服务契约(XSD/WSDL)
在
src/main/resources/schemas
目录下创建
countries.xsd
:
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://example.com/countries"
xmlns:tns="http://example.com/countries"
elementFormDefault="qualified">
<xs:element name="GetCountryRequest">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="GetCountryResponse">
<xs:complexType>
<xs:sequence>
<xs:element name="country" type="tns:country"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="country">
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="capital" type="xs:string"/>
<xs:element name="currency" type="tns:currency"/>
<xs:element name="population" type="xs:int"/>
</xs:sequence>
</xs:complexType>
<xs:simpleType name="currency">
<xs:restriction base="xs:string">
<xs:enumeration value="USD"/>
<xs:enumeration value="EUR"/>
<xs:enumeration value="GBP"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>
执行
mvn compile
命令后,JAXB将在
target/generated-sources
目录生成对应的Java类。
3. 实现数据仓储层
创建内存型国家数据仓库:
@Component
public class CountryRepository {
private static final Map<String, Country> countries = new ConcurrentHashMap<>();
@PostConstruct
public void initData() {
Country china = new Country();
china.setName("China");
china.setCapital("Beijing");
china.setCurrency(Currency.USD);
china.setPopulation(1412000000);
countries.put(china.getName(), china);
Country france = new Country();
france.setName("France");
france.setCapital("Paris");
france.setCurrency(Currency.EUR);
france.setPopulation(67390000);
countries.put(france.getName(), france);
}
public Country findCountry(String name) {
return countries.get(name);
}
}
4. 构建SOAP服务端点
创建处理SOAP请求的端点类:
@Endpoint
public class CountryEndpoint {
private static final String NAMESPACE_URI = "http://example.com/countries";
private final CountryRepository countryRepository;
public CountryEndpoint(CountryRepository countryRepository) {
this.countryRepository = countryRepository;
}
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "GetCountryRequest")
@ResponsePayload
public GetCountryResponse getCountry(@RequestPayload GetCountryRequest request) {
GetCountryResponse response = new GetCountryResponse();
response.setCountry(countryRepository.findCountry(request.getName()));
if(response.getCountry() == null) {
throw new CountryNotFoundException("Country not found: " + request.getName());
}
return response;
}
}
实现自定义SOAP Fault处理:
@ControllerAdvice
public class EndpointExceptionHandler {
@ExceptionHandler(CountryNotFoundException.class)
public void handleCountryNotFoundException(CountryNotFoundException ex,
SoapMessage message) throws IOException {
SoapFault fault = new SoapFault(ex.getMessage(),
SoapFault.FAULT_CODE_CLIENT);
fault.setFaultStringOrReason(ex.getMessage());
message.setFault(fault);
}
}
5. 服务配置与WSDL发布
配置Spring WS基础设置:
@EnableWs
@Configuration
public class WebServiceConfig extends WsConfigurerAdapter {
@Bean
public ServletRegistrationBean<MessageDispatcherServlet> 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://example.com/countries");
wsdl11Definition.setSchema(countriesSchema);
return wsdl11Definition;
}
@Bean
public XsdSchema countriesSchema() {
return new SimpleXsdSchema(
new ClassPathResource("schemas/countries.xsd"));
}
}
6. 高级SOAP特性实现
6.1 SOAP Header处理
扩展端点以处理认证Header:
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "GetCountryRequest")
@ResponsePayload
public GetCountryResponse getCountry(
@RequestPayload GetCountryRequest request,
@SoapHeader("{" + SECURITY_NS + "}Authentication") Source securityHeader) {
try {
// 解析Header内容
String authToken = extractAuthToken(securityHeader);
if(!validateToken(authToken)) {
throw new AuthenticationException("Invalid auth token");
}
// 处理业务逻辑
return processRequest(request);
} catch (Exception e) {
throw new SoapFaultClientException(e);
}
}
6.2 消息日志拦截
添加SOAP消息日志拦截器:
@Bean
public WsConfigurerAdapter wsConfigurerAdapter() {
return new WsConfigurerAdapter() {
@Override
public void addInterceptors(List<EndpointInterceptor> interceptors) {
interceptors.add(new PayloadLoggingInterceptor());
interceptors.add(new SoapEnvelopeLoggingInterceptor());
}
};
}
class SoapEnvelopeLoggingInterceptor extends PayloadLoggingInterceptor {
@Override
protected Source getSource(MessageContext messageContext) {
return messageContext.getRequest() instanceof SoapMessage ?
((SoapMessage)messageContext.getRequest()).getEnvelope().getSource() :
super.getSource(messageContext);
}
}
7. 测试与验证
使用Postman测试SOAP服务:
-
获取WSDL定义:
GET http://localhost:8080/ws/countries.wsdl -
发送SOAP请求示例:
POST /ws HTTP/1.1 Host: localhost:8080 Content-Type: text/xml;charset=UTF-8 SOAPAction: "" <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:cou="http://example.com/countries"> <soapenv:Header> <cou:Authentication> <cou:Token>SECRET_KEY</cou:Token> </cou:Authentication> </soapenv:Header> <soapenv:Body> <cou:GetCountryRequest> <cou:name>China</cou:name> </cou:GetCountryRequest> </soapenv:Body> </soapenv:Envelope> -
预期响应示例:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Header/> <SOAP-ENV:Body> <ns2:GetCountryResponse xmlns:ns2="http://example.com/countries"> <ns2:country> <ns2:name>China</ns2:name> <ns2:capital>Beijing</ns2:capital> <ns2:currency>USD</ns2:currency> <ns2:population>1412000000</ns2:population> </ns2:country> </ns2:GetCountryResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope>
8. 性能优化建议
-
启用HTTP压缩 :
# application.properties server.compression.enabled=true server.compression.mime-types=text/xml -
配置JAXB上下文缓存 :
@Bean public Jaxb2Marshaller marshaller() { Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); marshaller.setContextPath("com.example.countries"); marshaller.setMtomEnabled(true); // 启用MTOM附件优化 return marshaller; } -
使用SAX解析器提升性能 :
@Bean public SaajSoapMessageFactory messageFactory() { SaajSoapMessageFactory factory = new SaajSoapMessageFactory(); factory.setMessageFactory(MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL)); return factory; }
实际项目中,建议结合Spring Boot Actuator监控端点
/actuator/httptrace
来跟踪SOAP请求性能指标。对于高并发场景,可以考虑引入异步处理机制或增加WS-Security加密带来的性能开销。
341


&spm=1001.2101.3001.11974&articleId=84127493&d=1&t=3&u=c2f5d437d37746dbbe143ddd5b29e2f1)

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



