Web 服务支持

Web 服务支持

本章介绍了 Spring 集成对 Web 服务的支持,包括:spring-doc.cadn.net.cn

您需要将此依赖项包含在您的项目中:spring-doc.cadn.net.cn

Maven 系列
<dependency>
    <groupId>org.springframework.integration</groupId>
    <artifactId>spring-integration-ws</artifactId>
    <version>6.1.9</version>
</dependency>
Gradle
compile "org.springframework.integration:spring-integration-ws:6.1.9"

出站 Web 服务网关

要在向通道发送消息时调用 Web 服务,您有两个选项,这两个选项都基于 Spring Web 服务项目构建:SimpleWebServiceOutboundGatewayMarshallingWebServiceOutboundGateway. 前者接受Stringjavax.xml.transform.Source作为消息负载。 后者支持MarshallerUnmarshaller接口。 两者都需要 Spring Web 服务DestinationProvider来确定要调用的 Web 服务的 URI。 以下示例显示了调用 Web 服务的两个选项:spring-doc.cadn.net.cn

 simpleGateway = new SimpleWebServiceOutboundGateway(destinationProvider);

 marshallingGateway = new MarshallingWebServiceOutboundGateway(destinationProvider, marshaller);
当使用命名空间支持(稍后介绍)时,您只需设置一个 URI。 在内部,解析器配置一个固定的 URIDestinationProvider实现。 但是,如果您需要在运行时动态解析 URI,则DestinationProvider可以提供从注册表中查找 URI 等行为。 请参阅 Spring Web 服务DestinationProviderJavadoc 了解有关此策略的更多信息。

从版本 5.0 开始,您可以提供SimpleWebServiceOutboundGatewayMarshallingWebServiceOutboundGateway使用外部WebServiceTemplate实例,您可以为任何自定义属性配置该实例,包括checkConnectionForFault(这允许您的应用程序处理不合格的服务)。spring-doc.cadn.net.cn

有关内部工作原理的更多详细信息,请参阅 Spring Web 服务参考指南中涵盖客户端访问的章节和涵盖对象/XML 映射的章节。spring-doc.cadn.net.cn

入站 Web 服务网关

要在收到 Web 服务调用时向通道发送消息,您同样有两个选项:SimpleWebServiceInboundGatewayMarshallingWebServiceInboundGateway. 前者提取javax.xml.transform.SourceWebServiceMessage并将其设置为 Message payload。 后者支持实现MarshallerUnmarshaller接口。 如果传入的 Web 服务消息是 SOAP 消息,则 SOAP作标头将添加到Message转发到 Request 通道。 以下示例显示了这两个选项:spring-doc.cadn.net.cn

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

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

这两个网关都实现了 Spring Web 服务MessageEndpoint接口,因此它们可以配置一个MessageDispatcherServlet根据标准 Spring Web 服务配置。spring-doc.cadn.net.cn

有关如何使用这些组件的更多详细信息,请参见 Spring Web 服务参考指南中介绍创建 Web 服务的章节。 介绍 Object/XML 映射的章节也同样适用。spring-doc.cadn.net.cn

要添加SimpleWebServiceInboundGatewayMarshallingWebServiceInboundGateway配置添加到 Spring WS 基础结构中,您应该添加EndpointMapping定义MessageDispatcherServlet和目标MessageEndpoint实现,就像你对普通的 Spring WS 应用程序所做的那样。 为此(从 Spring 集成的角度来看),Spring WS 提供了以下方便的EndpointMapping实现:spring-doc.cadn.net.cn

您必须在应用程序上下文中为这些类指定 bean,并引用SimpleWebServiceInboundGateway和/或MarshallingWebServiceInboundGateway根据 WS 映射算法的 bean 定义。spring-doc.cadn.net.cn

有关更多信息,请参阅终端节点映射spring-doc.cadn.net.cn

Web 服务命名空间支持

要配置出站 Web 服务网关,请使用outbound-gateway元素wsnamespace 中,如下例所示:spring-doc.cadn.net.cn

<int-ws:outbound-gateway id="simpleGateway"
                     request-channel="inputChannel"
                     uri="https://example.org"/>
此示例不提供 'reply-channel'。 如果 Web 服务返回非空响应,则Message包含该响应的响应将发送到请求消息的REPLY_CHANNEL页眉。 如果这不可用,则会引发 channel resolution 异常。 如果要将回复发送到另一个通道,请在 'outbound-gateway' 元素上提供 'reply-channel' 属性。
默认情况下,当您调用在对请求使用 String 负载后返回空响应的 Web 服务时Message,没有回复Message已发送。 因此,你不需要设置 'reply-channel' 或有一个REPLY_CHANNEL标头Message. 如果您确实希望以Message,您可以将 'ignore-empty-responses' 属性设置为false. 这样做仅适用于String对象,因为使用SourceDocumentobject 导致 null 响应,因此永远不会生成回复Message.

要设置入站 Web Service Gateway,请使用inbound-gateway元素,如下例所示:spring-doc.cadn.net.cn

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

要使用 Spring OXM 编组器或解组器,必须提供 bean 引用。 以下示例说明如何为出站编组网关提供 Bean 引用:spring-doc.cadn.net.cn

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

下面的示例展示了如何为入站编组网关提供 Bean 引用:spring-doc.cadn.net.cn

<int-ws:inbound-gateway id="marshallingGateway"
                    request-channel="requestChannel"
                    marshaller="someMarshaller"
                    unmarshaller="someUnmarshaller"/>
Marshallerimplementation 还会实现Unmarshaller接口。 当使用这样的Marshaller,则只有marshaller属性是必需的。 即使使用Marshaller,您还可以为request-callback在出站网关上。

对于任一出站网关类型,您都可以指定destination-provider属性而不是uri(恰好需要其中之一)。 然后,您可以引用任何 Spring Web 服务DestinationProvider实现(例如,在运行时从注册表中查找 URI)。spring-doc.cadn.net.cn

对于任一出站网关类型,message-factory属性也可以配置对任何 Spring Web 服务的引用WebServiceMessageFactory实现。spring-doc.cadn.net.cn

对于简单入站网关类型,您可以设置extract-payload属性设置为false转发整个WebServiceMessage而不仅仅是其 payload 作为Message添加到请求通道。 这样做可能很有用,例如,当自定义转换器与WebServiceMessage径直。spring-doc.cadn.net.cn

从版本 5.0 开始,web-service-templatereference 属性允许您将WebServiceTemplate具有任何可能的自定义属性。spring-doc.cadn.net.cn

Web 服务 Java DSL 支持

以下代码段显示了 Web 服务命名空间支持中显示的网关的等效配置:spring-doc.cadn.net.cn

@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已为出站网关提供)。 例子:spring-doc.cadn.net.cn

.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 服务支持的所有 URI 方案(参见 URI 和传输) <uri-variable/>提供了 substitution 。 以下示例显示了如何定义它:spring-doc.cadn.net.cn

<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}&amp;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,则不支持变量替换,如果提供变量,则会发生配置错误。spring-doc.cadn.net.cn

控制 URI 编码

默认情况下,URL 字符串是编码的(请参阅UriComponentsBuilder) 添加到 URI 对象。 在某些具有非标准 URI 的方案中,不需要执行编码。 这<ws:outbound-gateway/>元素提供了一个encoding-mode属性。 要禁用 URL 编码,请将此属性设置为NONE(默认情况下,它是TEMPLATE_AND_VALUES). 如果您希望对某些 URL 进行部分编码,可以使用expression<uri-variable/>,如下例所示:spring-doc.cadn.net.cn

<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 集成 Web 服务网关会自动映射 SOAP作头。 默认情况下,它与 Spring 集成之间相互复制MessageHeaders通过使用DefaultSoapHeaderMapper.spring-doc.cadn.net.cn

您可以传入自己的特定于 SOAP 的头映射器的实现,因为网关具有支持这样做的属性。spring-doc.cadn.net.cn

除非requestHeaderNamesreplyHeaderNames的属性DefaultSoapHeaderMapper,则不会将任何用户定义的 SOAP 标头复制到 SOAP 消息或从 SOAP 消息复制任何用户定义的 SOAP 标头。spring-doc.cadn.net.cn

当您使用 XML 命名空间进行配置时,您可以使用mapped-request-headersmapped-reply-headers属性,您可以通过设置header-mapper属性。spring-doc.cadn.net.cn

映射用户定义的 Headers 时,值还可以包含简单的通配符模式(例如myheader*myheader). 例如,如果需要复制所有用户定义的标头,则可以使用通配符:.

从版本 4.1 开始,AbstractHeaderMapper(一个DefaultSoapHeaderMappersuperclass) 允许NON_STANDARD_HEADERStoken 的requestHeaderNamesreplyHeaderNames属性(除了现有的STANDARD_REQUEST_HEADERSSTANDARD_REPLY_HEADERS) 映射所有用户定义的标头。spring-doc.cadn.net.cn

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

从版本 4.3 开始,您可以通过在模式前面加上!. 否定模式获得优先级,因此STANDARD_REQUEST_HEADERS,thing1,thing*,!thing2,!thing3,qux,!thing1不映射thing1,thing2thing3. 它确实映射了标准标头,thing4qux. (请注意,thing1以非否定和否定形式包含。 因为否定的值优先,所以thing1未映射。spring-doc.cadn.net.cn

如果您有一个以!,则可以使用 进行转义,如下所示:\STANDARD_REQUEST_HEADERS,\!myBangHeader. 一个!myBangHeader然后映射。

入站 SOAP 标头(入站网关的请求标头和出站网关的回复标头)映射为SoapHeaderElement对象。 您可以通过访问Source:spring-doc.cadn.net.cn

<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*auth,catcanheaders 被映射,但qux未映射。spring-doc.cadn.net.cn

以下示例演示如何获取名为user从名为auth:spring-doc.cadn.net.cn

...
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>. 以下示例显示了如何执行此作:spring-doc.cadn.net.cn

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 信封:spring-doc.cadn.net.cn

<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 服务网关直接通过编组程序的内置功能(例如,Jaxb2Marshaller提供mtomEnabled选项)。 从版本 5.0 开始,简单 Web 服务网关可以直接使用入站和出站进行作MimeMessage实例,这些实例具有用于作附件的 API。 当您需要发送带有附件的 Web 服务消息(来自服务器的回复或客户端请求)时,您应该使用WebServiceMessageFactory直接发送WebServiceMessage将附件作为payload添加到网关的请求或回复通道。 以下示例显示了如何执行此作:spring-doc.cadn.net.cn

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));

APP信息