websocket服务端往往需要和服务层打交道,因此需要将服务层的一些bean注入到websocket实现类中使用,但是呢,websocket实现类虽然顶部加上了@Component注解,依然无法通过@Resource和@Autowire注入spring容器管理下的bean。后来就想用ApplicationContext获取spring容器管理下的bean。但是无法获取ApplicationContext的实例,因为该实例也是在spring下管理的,所以就又碰到前面的问题,当时都快崩溃了,这不是个死路吗,又回到原先的问题了。。后来在网上找到了该问题的解决办法,那就是在初始化ApplicationContext实例的时候将该引用保存到websocket类里。如下
@Component
@ServerEndpoint(value = "/messageSocket/{userId}")
public class MessageWebSocket {
/**
* 此处是解决无法注入的关键
*/
private static ApplicationContext applicationContext;
public static void setApplicationContext(ApplicationContext applicationContext) {
MessageWebSocket.applicationContext = applicationContext;
}
@OnOpen
public void onOpen(Session session, @PathParam("userId") Integer userId) {
}
@OnClose
public void onClose() {
}
@OnMessage
public void onMessage(String messageStr, Session session, @PathParam("userId") Integer userId) throws IOException {
//applicationContext使用
ThreadPoolTaskExecutor threadPoolTaskExecutor = (ThreadPoolTaskExecutor)applicationContext.getBean("defaultThreadPool");
}
@OnError
public void onError(Session session, Throwable error) {
}
}
然后在初始化ApplicationContext时(在springboot启动类中)对该类的MessageWebSocket进行赋值
public class WebApplication {
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(WebApplication.class);
ConfigurableApplicationContext configurableApplicationContext = springApplication.run(args);
//解决WebSocket不能注入的问题
MessageWebSocket.setApplicationContext(configurableApplicationContext);
}
}
思考:
为什么websocket注入不进bean呢(已经将其加入了spring管理了,而且其他类是能够注入websocket的实现bean)?
网上也没有这个问题的具体解释,我的感觉是websocket连接是需要创建多个线程的,其与spring自动注入有某种冲突,因此@Resource和@Autowire无法注入bean的引用。
|