59.3.2. 使用拦截器供应商 API
概述
拦截器可以使用任何实现在 拦截器供应商接口 中显示的 InterceptorProvider 接口的组件注册。
拦截器供应商接口
package org.apache.cxf.interceptor; import java.util.List; public interface InterceptorProvider { List<Interceptor<? extends Message>> getInInterceptors(); List<Interceptor<? extends Message>> getOutInterceptors(); List<Interceptor<? extends Message>> getInFaultInterceptors(); List<Interceptor<? extends Message>> getOutFaultInterceptors(); }
通过接口中的四个方法,您可以检索端点的拦截器链作为 Java List
对象。通过使用 Java List
对象提供的方法,开发人员可以在任何链中添加和移除拦截器。
流程
要使用 InterceptorProvider API 将拦截器附加到运行时组件的拦截器链,您必须:
使用拦截器要附加到的链,访问运行时组件。
开发人员必须使用 Apache CXF 特定的 API 访问标准 Java 应用代码的运行时组件。通常可以通过将 JAX-WS 或 JAX-RS 工件转换为基础 Apache CXF 对象来访问运行时组件。
- 创建拦截器的实例。
- 使用正确的 get 方法来检索所需的拦截器链。
使用
List
对象的add()
方法将拦截器附加到拦截器链。此步骤通常与检索拦截器链合并。
将拦截器附加到消费者
以编程方式将拦截器附加到消费者 显示将拦截器附加到 JAX-WS 消费者的入站拦截器链的代码。
以编程方式将拦截器附加到消费者
package com.fusesource.demo; import java.io.File; import java.net.URL; import javax.xml.namespace.QName; import javax.xml.ws.Service; import org.apache.cxf.endpoint.Client; public class Client { public static void main(String args[]) { QName serviceName = new QName("http://demo.eric.org", "stockQuoteReporter"); Service s = Service.create(serviceName); QName portName = new QName("http://demo.eric.org", "stockQuoteReporterPort"); s.addPort(portName, "http://schemas.xmlsoap.org/soap/", "http://localhost:9000/EricStockQuote"); quoteReporter proxy = s.getPort(portName, quoteReporter.class); Client cxfClient = (Client) proxy; ValidateInterceptor validInterceptor = new ValidateInterceptor(); cxfClient.getInInterceptor().add(validInterceptor); ... } }
以编程方式将拦截器附加到消费者 中的代码执行以下操作:
为消费者创建一个 JAX-WS Service
对象。
在提供消费者的目标地址的 Service
对象中添加端口。
创建用于在服务提供商上调用方法的代理。
将代理转换为 org.apache.cxf.endpoint.Client
类型。
创建拦截器的实例。
将拦截器附加到入站拦截器链。
将拦截器附加到服务供应商
以编程方式将拦截器附加到服务供应商 显示将拦截器附加到服务提供商的出站拦截器链的代码。
以编程方式将拦截器附加到服务供应商
package com.fusesource.demo; import java.util.*; import org.apache.cxf.endpoint.Server; import org.apache.cxf.frontend.ServerFactoryBean; import org.apache.cxf.frontend.EndpointImpl; public class stockQuoteReporter implements quoteReporter { ... public stockQuoteReporter() { ServerFactoryBean sfb = new ServerFactoryBean(); Server server = sfb.create(); EndpointImpl endpt = server.getEndpoint(); AuthTokenInterceptor authInterceptor = new AuthTokenInterceptor(); endpt.getOutInterceptor().add(authInterceptor); } }
以编程方式将拦截器附加到服务供应商 中的代码执行以下操作:
创建一个 ServerFactoryBean
对象,用于提供对底层 Apache CXF 对象的访问权限。
获取 Apache CXF 用来代表端点的服务器对象。
获取服务提供商的 Apache CXF EndpointImpl
对象。
创建拦截器的实例。
将拦截器附加到端点 ; 出站拦截器链。
将拦截器附加到总线
将拦截器附加到总线 显示将拦截器附加到总线入站拦截器链的代码。
将拦截器附加到总线
import org.apache.cxf.BusFactory; org.apache.cxf.Bus; ... Bus bus = BusFactory.getDefaultBus(); WatchInterceptor watchInterceptor = new WatchInterceptor(); bus..getInInterceptor().add(watchInterceptor); ...
将拦截器附加到总线 中的代码执行以下操作:
获取运行时实例的默认总线。
创建拦截器的实例。
将拦截器附加到入站拦截器链。
WatchInterceptor
将附加到由运行时实例创建的所有端点的入站拦截器链中。