Spring中@ServerEndpoint类下的@Resource或@Autowired无效

概述

@ServerEndpoint类下的@Resource@Autowired无效

下面的注入并没有成功

1
2
3
4
5
6
7
8
9
10
11

@Component
@Slf4j
public class WebSocketServer {

/**
* 聊天信息分发
*/
@Resource(name = "socketRouter")
private ISocketRouter socketRouter;
}

原因 1

在使用@ServerEndpoint 是多例的,与 spring 单例模式冲突,所以在当前类中只会注入一次.

解决方法

在加载当前 bean时,set方法会再次执行一次.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

@Component
@Slf4j
public class WebSocketServer {

/**
* 聊天信息分发
*/
private static ISocketRouter socketRouter;

@Resource(name = "socketRouter")
public void setEmployeeServer(ISocketRouter socketRouter) {
this.socketRouter = socketRouter;
}
}

本文地址: https://github.com/maxzhao-it/blog/post/58297/