@ServerEndpoint和@Autowired

时间:2015-03-27 17:39:20

标签: java spring websocket autowired

如何将字段自动装入@ServerEndpoint。以下不起作用。

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

但是,如果删除@ServerEndpoint,则可以正常使用。

我使用的是spring 3.2.1和Java 7

5 个答案:

答案 0 :(得分:6)

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

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

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

如果您不可行,则可以使用自己的ServerEndpointConfig.Configurator版本拦截使用ServerEndpoint注释的类的实例化过程。然后,您可以自己实例化该类,并使用BeanFactoryApplicationContext的实例对其进行自动装配。实际上,这种用法已有类似的答案。请参阅that question和Martins'working example(特别是,与Spring集成的自定义Configurator。)

答案 1 :(得分:3)

可以使用SpringConfigurator(spring 4)修复此问题:

将配置程序添加到ServerEndpoint:

@ServerEndpoint(value = "/ws", configurator = SpringConfigurator.class)

所需的maven依赖:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-websocket</artifactId>
    <version>${spring.version}</version>
</dependency>

答案 2 :(得分:2)

你应该可以将它实际添加到你的班级。:

@PostConstruct
public void init(){
    SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}

答案 3 :(得分:1)

我的解决方案是:

public WebsocketServletTest() {
      SpringApplicationListener.getApplicationContext().getAutowireCapableBeanFactory().autowireBean(this);
}

其中SpringApplicationListener是ApplicationContextAware,它将上下文存储在静态变量中

答案 4 :(得分:0)

JavaEE 7规范说

@ServerEndpoint
The annotated class must have a public no-arg constructor.
相关问题