【问题标题】:How to use CDI into JAX-RS client如何在 JAX-RS 客户端中使用 CDI
【发布时间】:2017-04-22 01:20:37
【问题描述】:

我在 SO 和官方文档上搜索了一段时间,但找不到直接将 CDI 注入 JAX-RS 客户端的方法。

我使用 builder 方法检索客户端,并且我想注册一个 WriterInterceptor(或任何类似过滤器的组件),它使用注入来检索另一个 bean。

我想使用 CDI 注入并避免向 HK2 注册每个 bean。

ClientBuilder.newBuilder()
            .register(MyWriter.class)
            .build();

MyWriter 和注入的类。

@Provider
public class MyWriter implements WriterInterceptor {
    private final MyRepo repo;

    @Inject
    public MyWriter(MyRepo repo) {
        this.repo = repo;
    }

    @Override
    public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
        context.proceed();
    }
}

public class MyRepo {

}

我正在使用 Jersey 2 和 Weld SE 在嵌入式码头中跑步。

【问题讨论】:

    标签: jersey jax-rs cdi embedded-jetty weld


    【解决方案1】:

    可以使用 wield 注入 java se 应用程序。

     @Singleton
    public class Application {
    
    private static Logger logger = LoggerFactory.getLogger(Application.class);
    
        @inject
        private SomeOtherBean injectedBean;
    
    public void run() {
        logger.debug("application initialized");
            injectedBean.doSomething();
    
    }
    
    }
    

    在 main 内部初始化 weild

    import java.io.IOException;
    
    import org.jboss.weld.environment.se.Weld;
    import org.jboss.weld.environment.se.WeldContainer;
    
    public class EntryPoint {
    
      public static void main(String[] args) throws IOException {
    
       Weld weld = new Weld();
       WeldContainer container = weld.initialize();
       Application application = container.instance().select(Application.class).get();
       application.run();
       weld.shutdown();
    
      }
    }
    

    看看下面的文档

    https://docs.jboss.org/weld/reference/latest/en-US/html/environments.html#_java_se

    也在下面的教程 https://randling.wordpress.com/2011/08/15/cdi-in-java-se/

    【讨论】:

    • 我已经在使用这种配置了。我的问题是关于在 JAX-RS 客户端中使用 CDI,因为 HK2 注入优先于 Weld。
    【解决方案2】:

    如果我理解正确,这已经被问到了,answered。简而言之:您必须覆盖 H2K Binder 的默认行为,因此它可以使用 Weld Bean Manager。以后不必为每个 Bean 注册 H2K。

    编辑:包含帖子中的所有内容,因此您不必阅读 cmets:

    【讨论】:

    • 这仅适用于服务器端,我已经实现了您参考的答案中描述的内容。
    • 确实,你是对的。 standard Client-side injection providersJersey Weld extentsion 的组合不应该在客户端发挥作用吗?
    • 我没有为客户更换定位器,手动查找仍然有效,但我想直接使用注入。
    • 似乎可行,但很老套,据我所知,Dropwizard 的人解决了这个问题:请参阅 this github ticket
    猜你喜欢
    • 1970-01-01
    • 2015-01-03
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2016-12-06
    • 2013-04-29
    • 2016-02-21
    • 1970-01-01
    相关资源
    最近更新 更多