本文介绍了@ServerEndpoint 和 @Autowired的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将字段自动连接到 @ServerEndpoint.以下方法无效.

How can I autowire a field into a @ServerEndpoint. The following does not work.

@Component
@ServerEndpoint("/ws")
public class MyWebSocket {
    @Autowired
    private ObjectMapper objectMapper;
}

但是,如果我删除 @ServerEndpoint,它就可以正常工作.

However if I remove the @ServerEndpoint, it works fine.

我使用的是 spring 3.2.1 和 Java 7

I am using spring 3.2.1 and Java 7

推荐答案

看来您正在尝试集成 Spring 和 Java WebSocket API.@Component 注释的类注册到一个spring bean,它的实例默认由spring 作为单例管理.但是,由 @ServerEndpoint 注释的类注册到服务器端 WebSocket 端点,并且每次相应端点的 WebSocket 连接到服务器时,其实例都由 JWA 实现创建和管理.因此,您不能同时使用这两个注释.

It seems that you are trying to integrate Spring and Java WebSocket API. A class annotated by @Component is registered to a spring bean and its instance is managed by spring as a singleton by default. However, a class annotated by @ServerEndpoint is registered to a server-side WebSocket endpoint and every time the corresponding endpoint's WebSocket is connected to the server, its instance is created and managed by JWA implementation. Therefore, you can't use both annotations together.

也许最简单的解决方法是使用 CDI 而不是 Spring.当然,您的服务器应该支持 CDI.

Maybe the simplest workaround is to use CDI instead of Spring. Of course, your server should support CDI.

@ServerEndpoint("/ws")
public class MyWebSocket {
    @Inject
    private ObjectMapper objectMapper;
}

如果您觉得不可行,您可以使用您自己的.然后,您可以自己实例化该类并使用 BeanFactoryApplicationContext 的实例自动装配它.实际上,这种用法已经有类似的答案.请参阅该问题和Martins的工作示例(特别是定制的配置器,用于与 Spring 集成.

If it's not feasible to you, you can intercept instantiation process of the class annotated with ServerEndpoint by using a your own version of ServerEndpointConfig.Configurator. Then, you can instantiate the class by yourself and autowire it using an instance of BeanFactory or ApplicationContext. Actually, there is already similar answer to this usage. See that question and Martins' working example (Especially, a customized Configurator for integration with Spring).

这篇关于@ServerEndpoint 和 @Autowired的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-09 15:19