5.8. Injections into client providers 注入到客户端提供者

在某些情况下,您可能需要将一些自定义类型为您的客户提供程序实例。JAX-RS 类型不需要像他们一样将参数传入 API 方法来注入。注入到客户端提供者(过滤器,拦截器)只需要将供应者注册为一个类。如果提供者被注册成为一个实例,那么运行时将不会注入提供者。原因是,该提供程序实例可以注册为多个客户端配置。例如 一个 ClientRequestFilter实例可以注册两个Client

为了解决一个自定义类型注入到为客户提供者的实例,使用ServiceLocatorClientProvider提取 ServiceLocator 可返回所需的注入。下面的示例演示如何利用 ServiceLocatorClientProvider:

Example 5.6. ServiceLocatorClientProvider example

  1. public static class MyRequestFilter implements ClientRequestFilter {
  2. // this injection does not work as filter is registered as an instance:
  3. // @Inject
  4. // private MyInjectedService service;
  5. @Override
  6. public void filter(ClientRequestContext requestContext) throws IOException {
  7. // use ServiceLocatorClientProvider to extract HK2 ServiceLocator from request
  8. final ServiceLocator locator = ServiceLocatorClientProvider.getServiceLocator(requestContext);
  9. // and ask for MyInjectedService:
  10. final MyInjectedService service = locator.getService(MyInjectedService.class);
  11. final String name = service.getName();
  12. ...
  13. }
  14. }

详见 ServiceLocatorClientProvider(和ServiceLocatorProvider 支持常见的 JAX-RS 组件)