Springboot使用WebSocket无法注入service的解决方法
因为websocket需要开一个自己的线程,如果采用注解的话就是把它当做一个普通的组件放在容器里,调用的时候会一直在spring的线程里,而不是自己独立的线程。所以无法注入service.
//获取全局容器
private ApplicationContext applicationContext;
//聊天逻辑层service
private ChatService chatService;
@OnOpen
public void onOpen(Session session, EndpointConfig config) {
//获取登录时存放httpSession的用户数据
HttpSession httpSession= (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
WebApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(httpSession.getServletContext());
User user = (User) httpSession.getAttribute("user");
this.applicationContext = applicationContext;
this.session = session;
this.username = user.getUsername();
this.chatService = (ChatService) applicationContext.getBean("chatService");
//绑定username与session
onLinesUser.put(username, session);
webSocketSet.add(this); //加入set中
}
既然 WebSocket 无法通过依赖注入的方式获取到 bean 对象,那我们直接从容器中取,不要IOC帮我们注入了,自给自足。
this.chatService = (ChatService) applicationContext.getBean(“chatService”);
注意这里是怎么获取到 bean的,这样获取 Bean 就是通过 byName 的方式获取 bean,可我们有名为 chatService的对象在IOC吗?
我们通过 @Service 注解 注入了一个对象,但是这个对象的名字是 chatServiceImpl 也就是类名的缩写。
@Service
public class ChatServiceImpl implements ChatService {
}
当我们用 @Service(“chatService”) 注解 注入一个对象,那么这个对象的名字就叫 chatService
@Service("chatService")
public class ChatServiceImpl implements ChatService {
}
当然,我们也可以使用 byType类型注入对象到 IOC 容器里面。
this.chatService = (ChatService) applicationContext.getBean(ChatService.class);