springboot集成websocket,如果需要在websocket类中调用service或者mapper方法, 直接在websocket类中用@autowired来注入依赖是会报无法找到bean类的错误,下面就是错误的示例:
@Service
@ServerEndpoint("/api/ws")
public class WebSocketServer {
private Session session;
@Autowired
ItemMapper itemMapper;
@OnOpen
public void onOpen(Session session) {
this.session = session;
Item item = itemMapper.getItem();
}
为解决这个问题,可以使用 Spring 提供的 AutowireCapableBeanFactory 来手动注入依赖。首先,我们在springboot的启动类注入 AutowireCapableBeanFactory 实例,如下:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class YourApplication {
@Autowired
private ApplicationContext applicationContext;
@Bean
public AutowireCapableBeanFactory autowireCapableBeanFactory() {
return applicationContext.getAutowireCapableBeanFactory();
}
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
然后在 WebSocket 实现类中使用 AutowireCapableBeanFactory 完成手动注入。
@Service
@ServerEndpoint("/api/ws")
public class WebSocketServer {
private Session session;
ItemMapper itemMapper;
private static AutowireCapableBeanFactory beanFactory;
@Autowired
public void setBeanFactory(AutowireCapableBeanFactory beanFactory) {
WebSocketServer.beanFactory = beanFactory;
}
@OnOpen
public void onOpen(Session session) {
this.session = session;
this.itemMapper = beanFactory.getBean(ItemMapper.class);
Item item = itemMapper.getItem();
}
这样调用service或者mapper就不会报错了.