Web Services 支持

本章描述了 Spring Integration 对 Web Services 的支持,包括:

你需要将此依赖项添加到你的项目中:

  • Maven

  • Gradle

<dependency>
    <groupId>org.springframework.integration</groupId>
    <artifactId>spring-integration-ws</artifactId>
    <version>{project-version}</version>
</dependency>
compile "org.springframework.integration:spring-integration-ws:{project-version}"

出站 Web Service 网关

当向通道发送消息时调用 Web Service,你有两个选项,它们都基于 Spring Web Services 项目:SimpleWebServiceOutboundGatewayMarshallingWebServiceOutboundGateway。 前者接受 Stringjavax.xml.transform.Source 作为消息负载。 后者支持 MarshallerUnmarshaller 接口的任何实现。 两者都需要一个 Spring Web Services DestinationProvider 来确定要调用的 Web Service 的 URI。 以下示例显示了调用 Web Service 的两种选项:

 simpleGateway = new SimpleWebServiceOutboundGateway(destinationProvider);

 marshallingGateway = new MarshallingWebServiceOutboundGateway(destinationProvider, marshaller);

当使用命名空间支持(webservices-namespace)时,你只需设置一个 URI。 在内部,解析器会配置一个固定 URI 的 DestinationProvider 实现。 然而,如果你需要在运行时动态解析 URI,DestinationProvider 可以提供这种行为,例如从注册表中查找 URI。 有关此策略的更多信息,请参阅 Spring Web Services DestinationProvider Javadoc。

从 5.0 版本开始,你可以为 SimpleWebServiceOutboundGatewayMarshallingWebServiceOutboundGateway 提供一个外部 WebServiceTemplate 实例,你可以为任何自定义属性配置它,包括 checkConnectionForFault(这允许你的应用程序处理不符合规范的服务)。

有关内部工作原理的更多详细信息,请参阅 Spring Web Services 参考指南中关于 客户端访问 的章节以及关于 对象/XML 映射 的章节。

入站 Web Service 网关

要在收到 Web Service 调用时向通道发送消息,你再次有两个选项:SimpleWebServiceInboundGatewayMarshallingWebServiceInboundGateway。 前者从 WebServiceMessage 中提取 javax.xml.transform.Source 并将其设置为消息负载。 后者支持 MarshallerUnmarshaller 接口的实现。 如果传入的 Web Service 消息是 SOAP 消息,则 SOAP 动作头将添加到转发到请求通道的 Message 的头中。 以下示例显示了两种选项:

 simpleGateway = new SimpleWebServiceInboundGateway();
 simpleGateway.setRequestChannel(forwardOntoThisChannel);
 simpleGateway.setReplyChannel(listenForResponseHere); //Optional

 marshallingGateway = new MarshallingWebServiceInboundGateway(marshaller);
 //set request and optionally reply channel

这两个网关都实现了 Spring Web Services MessageEndpoint 接口,因此它们可以像标准 Spring Web Services 配置一样与 MessageDispatcherServlet 配置。

有关如何使用这些组件的更多详细信息,请参阅 Spring Web Services 参考指南中关于 创建 Web Service 的章节。 关于 对象/XML 映射 的章节也再次适用。

要将 SimpleWebServiceInboundGatewayMarshallingWebServiceInboundGateway 配置添加到 Spring WS 基础设施中,你应该在 MessageDispatcherServlet 和目标 MessageEndpoint 实现之间添加 EndpointMapping 定义,就像你对普通 Spring WS 应用程序所做的那样。 为此(从 Spring Integration 的角度来看),Spring WS 提供了以下方便的 EndpointMapping 实现:

  • o.s.ws.server.endpoint.mapping.UriEndpointMapping

  • o.s.ws.server.endpoint.mapping.PayloadRootQNameEndpointMapping

  • o.s.ws.soap.server.endpoint.mapping.SoapActionEndpointMapping

  • o.s.ws.server.endpoint.mapping.XPathPayloadEndpointMapping

你必须在应用程序上下文中为这些类指定 bean,并根据 WS 映射算法引用 SimpleWebServiceInboundGateway 和/或 MarshallingWebServiceInboundGateway bean 定义。

有关更多信息,请参阅 端点映射

Web Service 命名空间支持

要配置出站 Web Service 网关,请使用 ws 命名空间中的 outbound-gateway 元素,如以下示例所示:

<int-ws:outbound-gateway id="simpleGateway"
                     request-channel="inputChannel"
                     uri="https://example.org"/>

此示例未提供“reply-channel”。 如果 Web Service 返回非空响应,则包含该响应的 Message 将发送到请求消息的 REPLY_CHANNEL 头中定义的回复通道。 如果该通道不可用,则会抛出通道解析异常。 如果你想将回复发送到另一个通道,请在“outbound-gateway”元素上提供“reply-channel”属性。

默认情况下,当你在请求 Message 中使用 String 负载后调用返回空响应的 Web Service 时,不会发送回复 Message。 因此,你无需设置“reply-channel”或在请求 Message 中包含 REPLY_CHANNEL 头。 如果你确实希望将空响应作为 Message 接收,可以将“ignore-empty-responses”属性设置为 false。 这样做仅适用于 String 对象,因为使用 SourceDocument 对象会导致 null 响应,从而永远不会生成回复 Message

要设置入站 Web Service 网关,请使用 inbound-gateway 元素,如以下示例所示:

<int-ws:inbound-gateway id="simpleGateway"
                    request-channel="inputChannel"/>

要使用 Spring OXM 编组器或解组器,你必须提供 bean 引用。 以下示例显示了如何为出站编组网关提供 bean 引用:

<int-ws:outbound-gateway id="marshallingGateway"
                     request-channel="requestChannel"
                     uri="https://example.org"
                     marshaller="someMarshaller"
                     unmarshaller="someUnmarshaller"/>

以下示例显示了如何为入站编组网关提供 bean 引用:

<int-ws:inbound-gateway id="marshallingGateway"
                    request-channel="requestChannel"
                    marshaller="someMarshaller"
                    unmarshaller="someUnmarshaller"/>

大多数 Marshaller 实现也实现了 Unmarshaller 接口。 当使用这样的 Marshaller 时,只需要 marshaller 属性。 即使在使用 Marshaller 时,你也可以为出站网关上的 request-callback 提供引用。

对于任何一种出站网关类型,你可以指定 destination-provider 属性而不是 uri(两者中必须有且只有一个)。 然后,你可以引用任何 Spring Web Services DestinationProvider 实现(例如,在运行时从注册表中查找 URI)。

对于任何一种出站网关类型,message-factory 属性也可以配置为引用任何 Spring Web Services WebServiceMessageFactory 实现。

对于简单入站网关类型,你可以将 extract-payload 属性设置为 false,以将整个 WebServiceMessage 而不是仅仅其负载作为 Message 转发到请求通道。 这样做可能很有用,例如,当自定义转换器直接处理 WebServiceMessage 时。

从 5.0 版本开始,web-service-template 引用属性允许你注入具有任何可能自定义属性的 WebServiceTemplate

Web Service Java DSL 支持

webservices-namespace 中所示网关的等效配置显示在以下代码片段中:

@Bean
IntegrationFlow inbound() {
    return IntegrationFlow.from(Ws.simpleInboundGateway()
                .id("simpleGateway"))
        ...
        .get();
}
@Bean
IntegrationFlow outboundMarshalled() {
    return f -> f.handle(Ws.marshallingOutboundGateway()
                    .id("marshallingGateway")
                    .marshaller(someMarshaller())
                    .unmarshaller(someUnmarshalller()))
        ...
}
@Bean
IntegrationFlow inboundMarshalled() {
    return IntegrationFlow.from(Ws.marshallingInboundGateway()
                .marshaller(someMarshaller())
                .unmarshaller(someUnmarshalller())
                .id("marshallingGateway"))
        ...
        .get();
}

其他属性可以通过流畅的方式在端点规范上设置(属性取决于是否为出站网关提供了外部 WebServiceTemplate)。 示例:

.from(Ws.simpleInboundGateway()
                .extractPayload(false))
.handle(Ws.simpleOutboundGateway(template)
            .uri(uri)
            .sourceExtractor(sourceExtractor)
            .encodingMode(DefaultUriBuilderFactory.EncodingMode.NONE)
            .headerMapper(headerMapper)
            .ignoreEmptyResponses(true)
            .requestCallback(requestCallback)
            .uriVariableExpressions(uriVariableExpressions)
            .extractPayload(false))
)
.handle(Ws.marshallingOutboundGateway()
            .destinationProvider(destinationProvider)
            .marshaller(marshaller)
            .unmarshaller(unmarshaller)
            .messageFactory(messageFactory)
            .encodingMode(DefaultUriBuilderFactory.EncodingMode.VALUES_ONLY)
            .faultMessageResolver(faultMessageResolver)
            .headerMapper(headerMapper)
            .ignoreEmptyResponses(true)
            .interceptors(interceptor)
            .messageSenders(messageSender)
            .requestCallback(requestCallback)
            .uriVariableExpressions(uriVariableExpressions))
.handle(Ws.marshallingOutboundGateway(template)
            .uri(uri)
            .encodingMode(DefaultUriBuilderFactory.EncodingMode.URI_COMPONENT)
            .headerMapper(headerMapper)
            .ignoreEmptyResponses(true)
            .requestCallback(requestCallback)
            .uriVariableExpressions(uriVariableExpressions))
)

出站 URI 配置

对于 Spring Web Services 支持的所有 URI 方案(请参阅 URIs and Transports),提供了 <uri-variable/> 替换。 以下示例显示了如何定义它:

<ws:outbound-gateway id="gateway" request-channel="input"
        uri="https://springsource.org/{thing1}-{thing2}">
    <ws:uri-variable name="thing1" expression="payload.substring(1,7)"/>
    <ws:uri-variable name="thing2" expression="headers.x"/>
</ws:outbound-gateway>

<ws:outbound-gateway request-channel="inputJms"
        uri="jms:{destination}?deliveryMode={deliveryMode}&priority={priority}"
        message-sender="jmsMessageSender">
    <ws:uri-variable name="destination" expression="headers.jmsQueue"/>
    <ws:uri-variable name="deliveryMode" expression="headers.deliveryMode"/>
    <ws:uri-variable name="priority" expression="headers.jms_priority"/>
</ws:outbound-gateway>

如果你提供了 DestinationProvider,则不支持变量替换,并且如果你提供了变量,则会发生配置错误。

控制 URI 编码

默认情况下,URL 字符串在发送请求之前被编码(请参阅 UriComponentsBuilder)为 URI 对象。 在某些非标准 URI 的场景中,执行编码是不希望的。 <ws:outbound-gateway/> 元素提供了一个 encoding-mode 属性。 要禁用 URL 编码,请将此属性设置为 NONE(默认情况下为 TEMPLATE_AND_VALUES)。 如果你希望部分编码 URL,可以通过在 <uri-variable/> 中使用 expression 来实现,如以下示例所示:

<ws:outbound-gateway url="https://somehost/%2f/fooApps?bar={param}" encoding-mode="NONE">
          <http:uri-variable name="param"
            expression="T(org.apache.commons.httpclient.util.URIUtil)
                                             .encodeWithinQuery('Hello World!')"/>
</ws:outbound-gateway>

如果你设置了 DestinationProvider,则 encoding-mode 将被忽略。

WS 消息头

Spring Integration Web Service 网关会自动映射 SOAP 动作头。 默认情况下,它通过使用 DefaultSoapHeaderMapper 在 Spring Integration MessageHeaders 之间复制。

你可以传入自己实现的 SOAP 特定头映射器,因为网关具有支持这样做的属性。

除非 DefaultSoapHeaderMapperrequestHeaderNamesreplyHeaderNames 属性明确指定,否则任何用户定义的 SOAP 头都不会复制到或从 SOAP 消息中复制。

当你使用 XML 命名空间进行配置时,你可以通过使用 mapped-request-headersmapped-reply-headers 属性设置这些属性,你可以通过设置 header-mapper 属性提供自定义映射器。

在映射用户定义的头时,值也可以包含简单的通配符模式(例如 myheader*myheader)。 例如,如果你需要复制所有用户定义的头,你可以使用通配符字符:

从 4.1 版本开始,AbstractHeaderMapperDefaultSoapHeaderMapper 的超类)允许为 requestHeaderNamesreplyHeaderNames 属性配置 NON_STANDARD_HEADERS 令牌(除了现有的 STANDARD_REQUEST_HEADERSSTANDARD_REPLY_HEADERS)来映射所有用户定义的头。

我们建议使用以下组合:STANDARD_REPLY_HEADERS, NON_STANDARD_HEADERS,而不是使用通配符 (*)。 这样做可以避免将 request 头映射到回复。

从 4.3 版本开始,你可以通过在模式前加上 ! 来否定头映射中的模式。 否定模式具有优先级,因此像 STANDARD_REQUEST_HEADERS,thing1,thing*,!thing2,!thing3,qux,!thing1 这样的列表不会映射 thing1thing2thing3。 它会映射标准头、thing4qux。 (请注意,thing1 包含在非否定和否定形式中。由于否定值优先,thing1 不会被映射。)

如果你有一个以 ! 开头的用户定义头,并且你确实希望映射它,你可以使用 \ 对其进行转义,如下所示:STANDARD_REQUEST_HEADERS,\!myBangHeader。 然后 !myBangHeader 将被映射。

入站 SOAP 头(入站网关的请求头和出站网关的回复头)被映射为 SoapHeaderElement 对象。 你可以通过访问 Source 来探索其内容:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Header>
        <auth>
            <username>user</username>
            <password>pass</password>
        </auth>
        <bar>BAR</bar>
        <baz>BAZ</baz>
        <qux>qux</qux>
    </soapenv:Header>
    <soapenv:Body>
        ...
    </soapenv:Body>
</soapenv:Envelope>

如果 mapped-request-headersauth, ca*,则 authcatcan 头被映射,但 qux 未被映射。

以下示例显示了如何从名为 auth 的头中获取名为 user 的值:

...
SoapHeaderElement header = (SoapHeaderElement) headers.get("auth");
DOMSource source = (DOMSource) header.getSource();
NodeList nodeList = source.getNode().getChildNodes();
assertEquals("username", nodeList.item(0).getNodeName());
assertEquals("user", nodeList.item(0).getFirstChild().getNodeValue());
...

从 5.0 版本开始,DefaultSoapHeaderMapper 支持 javax.xml.transform.Source 类型的用户定义头,并将其填充为 <soapenv:Header> 的子节点。 以下示例显示了如何执行此操作:

Map<String, Object> headers = new HashMap<>();

String authXml =
     "<auth xmlns='http://test.auth.org'>"
           + "<username>user</username>"
           + "<password>pass</password>"
           + "</auth>";
headers.put("auth", new StringSource(authXml));
...
DefaultSoapHeaderMapper mapper = new DefaultSoapHeaderMapper();
mapper.setRequestHeaderNames("auth");

前面示例的结果是以下 SOAP 信封:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Header>
        <auth xmlns="http://test.auth.org">
            <username>user</username>
            <password>pass</password>
        </auth>
    </soapenv:Header>
    <soapenv:Body>
        ...
    </soapenv:Body>
</soapenv:Envelope>

MTOM 支持

编组入站和出站 Web Service 网关直接通过编组器(例如,Jaxb2Marshaller 提供 mtomEnabled 选项)的内置功能支持附件。 从 5.0 版本开始,简单 Web Service 网关可以直接使用入站和出站 MimeMessage 实例,这些实例具有操作附件的 API。 当你需要发送带有附件的 Web Service 消息(无论是来自服务器的回复还是客户端请求)时,你应该直接使用 WebServiceMessageFactory 并将带有附件的 WebServiceMessage 作为 payload 发送到网关的请求或回复通道。 以下示例显示了如何执行此操作:

WebServiceMessageFactory messageFactory = new SaajSoapMessageFactory(MessageFactory.newInstance());
MimeMessage webServiceMessage = (MimeMessage) messageFactory.createWebServiceMessage();

String request = "<test>foo</test>";

TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
transformer.transform(new StringSource(request), webServiceMessage.getPayloadResult());

webServiceMessage.addAttachment("myAttachment", new ByteArrayResource("my_data".getBytes()), "plain/text");

this.webServiceChannel.send(new GenericMessage<>(webServiceMessage));