Java @ServerEndpoint和@Autowired

Java @ServerEndpoint和@Autowired,java,spring,websocket,autowired,Java,Spring,Websocket,Autowired,如何将字段自动关联到@ServerEndpoint。以下方法不起作用 @Component @ServerEndpoint("/ws") public class MyWebSocket { @Autowired private ObjectMapper objectMapper; } 但是,如果我删除@ServerEndpoint,它可以正常工作 我正在使用Spring3.2.1和Java7 @ServerEndpoint The annotated class mus

如何将字段自动关联到@ServerEndpoint。以下方法不起作用

@Component
@ServerEndpoint("/ws")
public class MyWebSocket {   
    @Autowired
    private ObjectMapper objectMapper;
}
但是,如果我删除
@ServerEndpoint
,它可以正常工作


我正在使用Spring3.2.1和Java7

@ServerEndpoint
The annotated class must have a public no-arg constructor.

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

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

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

如果不可行,您可以使用自己版本的。然后,您可以自己实例化该类,并使用
BeanFactory
ApplicationContext
的实例自动连接该类。实际上,这个用法已经有了类似的答案。请参阅和Martins(特别是为与Spring集成而定制的)。

实际上,您应该能够将其添加到您的类中:

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

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

将configurator添加到您的ServerEndpoint:

@ServerEndpoint(value = "/ws", configurator = SpringConfigurator.class)
所需的maven依赖项:

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

org.springframework
弹簧网袋
${spring.version}
我的解决方案是:

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

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

是否收到任何错误?objectMapper为null。它没有被注入/autowiredI没有显示在示例中,但类中已经有一个默认构造函数。感谢您的回答。非常有用。虽然我刚升级到Spring4,它有自己的WebSocket实现类,如果我把它添加到我的构造函数中,这行就可以运行了,但不是我的JavaxWebSocket调用的postConstruct。