webSocket
1.WebSocketServer里是无法通过@autowired或者@resource注入bean的
- 原因:spring容器管理的是单例的,他只会注入一次,而websocket是多对象的,当有新的用户使用的时候,他就会新创建一个websocket对象,这就导致了用户创建的websocket对象都不能注入对象了,所以在运行的时候就会发生注入对象为null的情况
- 方案
@ServerEndpoint("/url/{id}/{name}")
@Component
public class InternalWebsocketServer implements ApplicationContextAware {
private static Aservice aservice;
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
InternalWebsocketServer.applicationContext = applicationContext;
}
@PostConstruct
public void init() {
aservice = applicationContext.getBean(Aservice.class);
System.out.println("websocket 加载");
}
2.如果是打包成war到外部tomcat运行,则不需要WebSocketConfig.java这个配置类
@Configuration
public class WebsocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
- 该配置为了自动注册使用了@ServerEndpoint注解声明的 Websocket endpoint,开发阶段该配置会自动依赖springboot内嵌tomcat容器。
- war包的项目内嵌tomcat是不会在打包之后运行的,也就是说打包之后websocket没有依赖到tomcat容器,所以只需要把上面的配置类删除即可
- @ServerEndpoint
注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端, 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端。即 @ServerEndpoint 可以把当前类变成websocket服务类。