【问题标题】:Using CDI/injection in Tomcat Websocket / Serverendpoint在 Tomcat Websocket / Serverendpoint 中使用 CDI/注入
【发布时间】:2018-12-13 00:45:57
【问题描述】:

我正在使用 tomcat 9.0.4 和 Java 1.8。在同一个项目中,jersey 提供了一个 Web 服务。我可以使用 webservice 类中的 @Inject 没有任何问题。我正在尝试从下面的 websocket 端点显示进行注入。

@ApplicationScoped
@ServerEndpoint("/endpoint")
public class ArchApi {

  @Inject RepClass injectedClass;

  @OnMessage()
  public String onMessage(byte[] data) {
       injectedClass.doThings("test");
  }

}

这是我的 CDI 实现:

    <dependency>
        <groupId>org.glassfish.jersey.inject</groupId>
        <artifactId>jersey-hk2</artifactId>
        <version>2.27</version>
    </dependency>

我得到的只是一个java.lang.NullPointerException

我找到了这个feature 请求。所以我认为注入仍然没有在tomcat中实现。

我的问题:

  • 如何正确地将传入数据写入我的存储库?
  • 还有其他方法可以让 Injection 工作吗?

目前我正在考虑迁移到 glassfish,它应该支持从服务器端注入

【问题讨论】:

    标签: tomcat jersey cdi java-websocket tomcat9


    【解决方案1】:

    您可以使用以下配置器让 CDI 管理端点类:

    public class CdiAwareConfigurator extends ServerEndpointConfig.Configurator {
    
        public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {
            return CDI.current().select(endpointClass).get();
        }
    }
    

    然后将您的端点类注释如下:

    @ServerEndpoint(value = "/chat", configurator = CdiAwareConfigurator.class)
    public class ChatEndpoint {
        ...
    }
    

    根据您的 CDI 配置,您可能需要使用 @Dependent 注释端点类。


    或者,您可以使用以下方式以编程方式查找 bean 实例:

    SomeSortOfBean bean = CDI.current().select(SomeSortOfBean.class).get();
    

    【讨论】:

    • 谢谢,注入现在可以工作了(:但是我不能创建一个 entityManagerFactory。它是相关的吗?
    • @MrMueseli 可能不相关,但很难说您在问题中提供的详细程度。如果我的回答对您有用,请接受并在新问题中添加相关详细信息。
    猜你喜欢
    • 2014-01-29
    • 1970-01-01
    • 2014-01-19
    • 2017-02-16
    • 1970-01-01
    • 2015-02-28
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    相关资源
    最近更新 更多