繁体   English   中英

Undertow Websocket Bean注入CDI问题

[英]Undertow Websocket Bean Injection CDI Issue

我不明白为什么CDI使用注入不适用于使用undertow的websocket。

下面是我为一个简单的websocket端点编写的代码。

@ServerEndpoint("/")
public class TestWebSocketEndpoint {

    @Inject
    private RetrieveAccessor retrieveAccessor;

    private final Logger logger = Logger.getLogger(this.getClass().getName());

    @OnOpen
    public void onConnectionOpen(Session session) {
        logger.info("Connection opened ... " + session.getId());
    }

    @OnMessage
    public String onMessage(String message) {

        if (!message.isEmpty()) {
            return message;
        }

        System.out.println("RETRIEVE BEAN -> " + retrieveAccessor);
        if (retrieveAccessor != null) {
            return "BEAN NOT NULL";
        }
        return ":(";
    }

    @OnClose
    public void onConnectionClose(Session session) {
        logger.info("Connection close .... " + session.getId());
    }

}

当然,问题在于注入的属性为null。 我当然没有问题,使用其余的东西进行此部署和下面介绍的无状态Bean的注入。 有没有解决的办法,如果我只初始化需要的bean属性,会遇到什么问题? 因为那绝对可行。

RetrieveAccessor RetrieveAccessor = new .... {代码}

一种在@ServerEndpoint带注释的类上进行注入的简单方法是设置一个自定义配置器,该配置器通过重写getEndpointInstance(Class endpointClass)方法来使用CDI实例化端点实例的创建。

https://tyrus.java.net/documentation/1.13/user-guide.html#d0e464

带注释的端点:

@ServerEndpoint(value = "/", configurator = CDIEndpointConfigurator.class)
public class TestWebSocketEndpoint {
   ...
}

自定义配置器:

public class CDIEndpointConfigurator extends ServerEndpointConfig.Configurator {

    @Override
    public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException {
        return CDI.current().select(endpointClass).get();
    }
}

Undertow只是一个servlet容器。 Weld(或OWB)提供CDI支持。 我不确定如何实例化Undertow,但是您需要利用Weld(或其他一些CDI实现)。

这是一个示例。 利用CDI扩展来查找端点,一旦有了端点,就可以在Undertow中注册它们

随意利用Hammock。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM