Spring Web Services 2.0 发布

工程 | Arjen Poutsma | 2011 年 1 月 11 日 | ...

经过近一年的开发,我很高兴地宣布 Spring Web Services 2.0 已发布!在这篇文章中,我想介绍一些主要的新特性。

要求 Java 5+ 和 Spring 3.0

您可能知道,我们将对象 XML 映射 (OXM) 模块从 Spring-WS 项目移到了 Spring 3.0 中。因此,由于 org.springframework.oxm 包中存在冲突的类,将 Spring-WS 1.5(及其自己的 OXM 模块)与 Spring 3.0 一起使用会有些问题。

从 2.0 版本开始,我们不再将 OXM 模块作为 Spring-WS 的一部分发布,而是依赖于 Spring 的 OXM。因此,为了正常工作,Spring Web Services 2.0 要求使用 Spring 3.0。通常,我们对版本要求会更宽松一些,不一定要求最新的 Spring 版本,但这是唯一能让一切正常工作的方式。

由于依赖 Spring 3.0,我们也**要求使用 Java 5+**,并且整个代码库都使用了 Java 5 的特性(如泛型、可变参数和枚举)。例如,与 XPathTemplate 结合使用的 NodeMapper 接口现在是泛型的,因此不再需要进行强制类型转换


Person person = template.evaluateAsObject("//person", new DOMSource(document), new NodeMapper<Person>() {
    public Person mapNode(Node node, int nodeNum) throws DOMException {
        Element personElement = (Element) node;
        return new Person(personElement.getAttribute("firstName"), personElement.getAttribute("lastName"));
    }
});

请注意,即使我们升级了代码库以使用 Java 5+ 特性,我们仍然以向后兼容的方式进行。因此,Spring Web Services 2.0 向后兼容 1.5。不过,我们确实移除了已弃用的类。例如,XsdBasedSoap11Wsdl4jDefinitionBuilder 已被 DefaultWsdl11Definition 取代,后者具有相同的功能,但更具可定制性。

改进的 @Endpoint 编程模型

Spring Web Services 2.0 中最重要的一个新特性是能够在 @Endpoint 方法中使用任意参数类型。相对于 Spring-WS 1.5 的 @Endpoint 模型,一个巨大的改进是您现在可以混合和匹配参数,并且对返回类型的限制也更少。基本上,这使得 Spring-WS 的 @Endpoint 编程模型与 Spring 3 的 @Controller 模型旗鼓相当。

例如,您可以拥有以下 @Endpoint 方法


@PayloadRoot(localPart = "myRequest", namespace = "http://example.com")
@ResponsePayload
public MyJaxb2Response handleMyRequest(@RequestPayload org.w3c.dom.Element myElement, 
                                       SoapHeader requestHeader,
                                       MessageContext messageContext) {

    // do something interesting here
}

此方法将接收任何载荷根元素具有 "http://example.com" 命名空间和 "myRequest" 本地名称的 SOAP 消息。然后,此载荷将作为 W3C DOM 元素传递,并结合 SoapHeader(用于访问单个头元素)和整个消息上下文。

当前支持的参数/返回类型包括

  • DOM 元素(默认为 W3C DOM;如果 classpath 中存在 JDOM、dom4j、XOM,则会自动启用)
  • OXM Marshaller 支持的类型(需要显式配置 marshaller)
  • JAXB2 类型,如果 classpath 中存在 JAXB2(这意味着您不再需要显式配置 Jaxb2Marshaller)
  • javax.xml.transform.Source 及其子类型
  • StAX XMLStreamReader 和 XMLEventreaders。请注意,这些只能用作参数类型,不能用作返回类型。

要将请求消息的载荷获取为这些参数类型中的任何一种,您需要使用 @RequestPayload 注解参数。类似地,如果您希望返回值最终成为响应消息的载荷,您需要使用 @ResponsePayload 注解方法。这与 Spring 3 的 @Controller 模型非常相似,Spring 3 中有 @RequestBody 和 @ResponseBody,它们在 HTTP 领域提供了类似的功能。

此外,我们支持以下不带 @RequestPayload 的参数类型

  • MessageContext
  • SoapHeader, SoapBody, SoapEvelope(请求消息的)
  • @XPathParam 参数。请注意,您现在可以使用 @Namespace 和 @Namespaces 注解来指定 XPath 表达式中使用的任何命名空间,而不再需要在 XML 应用程序上下文中设置它们。例如
    
    @Namespaces(@Namespace(prefix = "tns", uri = "http://springframework.org/spring-ws"))
    public void myEndpointMethod(@XPathParam("/tns:root")String s) {
        // do something slightly more interesting here
    }
    

    这些命名空间注解(@Namespace 和 @Namespaces)可以出现在方法、类或包级别(即 package-info.java)上。

要启用此编程模型,您只需在 Spring Web Services 应用程序上下文中放置 <sws:annotation-driven/> 即可


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:sws="http://www.springframework.org/schema/web-services"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/web-services http://www.springframework.org/schema/web-services/web-services-2.0.xsd">

    <sws:annotation-driven/>

     <!-- other beans go here, or perhaps a <context:component-scan/> -->

</beans>

您可以选择为此元素提供 marshaller 和 unmarshaller 属性,分别指向一个 OXM Marshaller 和 Unmarshaller。这将启用支持使用此 marshaller 支持的类型作为 @RequestPayload/@ResponsePayload 类型。

请注意,我们也已弃用对 <sws:marshalling-endpoints/> 和 <sws:xpath-endpoints/> 的支持,转而支持 <sws:annotation-driven/>。因此,这两个元素在 XSD 模式的 2.0 版本中不存在,但在 1.5 版本中仍然存在。所以您可以选择继续使用模式的 1.5 版本,或者升级到 2.0 并使用 <sws:annotation-driven/>。

最后,与 Spring 中的所有内容一样,参数/返回类型机制是完全可插拔的。因此,如果您没有看到您想要的参数类型,请随时编写您自己的 MethodArgumentResolver 或 MethodReturnValueHandler,将其插入 Spring-WS,然后就可以使用了!

新的集成测试模块

另一个主要新特性是新的 Web 服务集成测试模块 spring-ws-test。此模块包含测试客户端(即使用 WebServiceTemplate 的类)和服务器(即 @Endpoints)的功能。客户端和服务器端测试模块都提供了“流畅”的 API,因此您通常可以在 IDE 中使用代码补全功能(即 ctrl-space)来指导您设置测试过程。

客户端集成测试

进行客户端集成测试的核心类是 MockWebServiceServer。其基本思想是 Web 服务模板连接到此模拟服务器,向其发送请求消息,然后模拟服务器根据已注册的预期进行验证。如果满足预期,模拟服务器就会准备一个响应消息,并将其发送回模板。

测试客户端代码的典型场景包括

  1. 创建 MockWebServiceServer。
  2. 设置关于请求消息的预期。
  3. 创建一个合适的响应消息
  4. 正常使用 WebServiceTemplate,无论是直接使用还是通过客户端代码使用。
  5. 调用 MockWebServiceServer.verify() 确保所有预期都已满足。

例如,考虑这个 Web 服务客户端类


import org.springframework.ws.client.core.support.WebServiceGatewaySupport;

public class CustomerClient extends WebServiceGatewaySupport {                           

  public int getCustomerCount() {
    CustomerCountRequest request = new CustomerCountRequest();                           
    request.setCustomerName("John Doe");

    CustomerCountResponse response =
      (CustomerCountResponse) getWebServiceTemplate().marshalSendAndReceive(request);    
      
    return response.getCustomerCount();
  }
}

CustomerClient 的典型测试如下所示


import javax.xml.transform.Source;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.xml.transform.StringSource;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.junit.Assert.assertEquals;

import org.springframework.ws.test.client.MockWebServiceServer;                          
import static org.springframework.ws.test.client.RequestMatchers.*;                      
import static org.springframework.ws.test.client.ResponseCreators.*;                     

@RunWith(SpringJUnit4ClassRunner.class)                                                  
@ContextConfiguration("integration-test.xml")                                            
public class CustomerClientIntegrationTest {

  @Autowired
  private CustomerClient client;                                                         

  private MockWebServiceServer mockServer;                                               

  @Before
  public void createServer() throws Exception {
    mockServer = MockWebServiceServer.createServer(client);
  }

  @Test
  public void customerClient() throws Exception {
    Source requestPayload = new StringSource(
      "<customerCountRequest xmlns='http://springframework.org/spring-ws'>" +
        "<customerName>John Doe</customerName>" +
      "</customerCountRequest>");
    Source responsePayload = new StringSource(
      "<customerCountResponse xmlns='http://springframework.org/spring-ws'>" +
        "<customerCount>10</customerCount>" +
      "</customerCountResponse>");

    mockServer.expect(payload(requestPayload)).andRespond(withPayload(responsePayload)); 

    int result = client.getCustomerCount();                                              
    assertEquals(10, result);                                                            

    mockServer.verify();                                                                 
  }
}

有关客户端测试的更多信息,请参考参考手册

服务器端集成测试

进行服务器端集成测试的核心类是 MockWebServiceClient。其基本思想是此客户端创建一个请求消息,然后将其发送到在标准 MessageDispatcherServlet 应用程序上下文中配置的端点。这些端点将处理消息并创建响应。然后客户端接收此响应,并根据已注册的预期对其进行验证。

MockWebServiceClient 的典型用法是

  1. 创建 MockWebServiceClient 实例。
  2. 发送请求消息。
  3. 设置响应预期。

例如,考虑这个简单的 Web 服务端点类


@Endpoint                                                                                
public class CustomerEndpoint {

  @ResponsePayload                                                                       
  public CustomerCountResponse getCustomerCount(                                         
      @RequestPayload CustomerCountRequest request) {                                    
    CustomerCountResponse response = new CustomerCountResponse();
    response.setCustomerCount(10);
    return response;
  }
}

CustomerEndpoint 的典型测试如下所示


import javax.xml.transform.Source;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.xml.transform.StringSource;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import org.springframework.ws.test.server.MockWebServiceClient;                          
import static org.springframework.ws.test.server.RequestCreators.*;                      
import static org.springframework.ws.test.server.ResponseMatchers.*;                     

@RunWith(SpringJUnit4ClassRunner.class)                                                  
@ContextConfiguration("spring-ws-servlet.xml")                                           
public class CustomerEndpointIntegrationTest {

  @Autowired
  private ApplicationContext applicationContext;                                         

  private MockWebServiceClient mockClient;

  @Before
  public void createClient() {
    mockClient = MockWebServiceClient.createClient(applicationContext);                  
  }

  @Test
  public void customerEndpoint() throws Exception {
    Source requestPayload = new StringSource(
      "<customerCountRequest xmlns='http://springframework.org/spring-ws'>" +
        "<customerName>John Doe</customerName>" +
      "</customerCountRequest>");
    Source responsePayload = new StringSource(
      "<customerCountResponse xmlns='http://springframework.org/spring-ws'>" +
        "<customerCount>10</customerCount>" +
      "</customerCountResponse>");

    mockClient.sendRequest(withPayload(requestPayload)).                                 
      andExpect(payload(responsePayload));                                               
  }
}

有关服务器端测试的更多信息,请参考参考手册

其他新特性

除了上面提到的主要特性,还有一些其他特性
  • Spring Web Services 2.0 引入了对 Spring Security 3.0 的支持
  • 支持 XMPP (Jabber) 传输

更多信息

如果你想尝试 Spring Web Services 2.0,可以访问站点,或直接前往下载页。如果你使用 Maven,升级应该很简单,只需添加以下仓库


<repository>
    <id>spring-release</id>
    <name>Spring Release Repository</name>
    <url>http://maven.springframework.org/release</url>
</repository>

然后可以像这样添加单个依赖项


<dependency>
    <groupId>org.springframework.ws</groupId>
    <artifactId>spring-ws-core</artifactId>
    <version>2.0.0.RELEASE</version>
</dependency>

这些 jar 应该很快就会在 Maven Central 上可用。

最后,我要感谢 Lukáš Křečan 和 Tareq Abed Rabbo。这两位社区成员在此版本的开发过程中提供了重要帮助。

获取 Spring 邮件列表

通过 Spring 邮件列表保持联系

订阅

快人一步

VMware 提供培训和认证,为您的进步注入强劲动力。

了解更多

获取支持

Tanzu Spring 通过一个简单的订阅提供 OpenJDK™、Spring 和 Apache Tomcat® 的支持和二进制文件。

了解更多

即将举行的活动

查看 Spring 社区所有即将举行的活动。

查看全部