@ServerEndpoint和@Autowired [英] @ServerEndpoint and @Autowired

查看:6286
本文介绍了@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;
}

如果你不可行,你可以拦截注释类的实例化过程使用您自己的 ServerEndpoint .Configurator.htmlrel =nofollow noreferrer> ServerEndpointConfig.Configurator 。然后,您可以自己实例化该类,并使用 BeanFactory ApplicationContext 的实例自动装配它。实际上,这种用法已有类似的答案。请参阅该问题和Martins'工作示例(特别是,自定义 Configurator 与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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆