1 Basic description
The websocket environment is configured in the project, and the message module is sent to the client. The variable cannot be injected, and the value is empty.
Spring manages singletons, which conflict with websockets (multiple objects).
When the project is initialized, it will initialize the websocket (non-user connected), and spring will also inject service for it. The service of the object is not null and is successfully injected. However, since spring manages a singleton by default, the service will only be injected once. When a new user enters the chat, the system will create a new websocket object. At this time, the contradiction appears: spring manages all singletons, and does not inject service into the second websocket object, so as long as the user is connected to create The websocket object can no longer be injected.
2 Solutions
Using method injection
private static DtsUserService dtsUserService;
private static DtsBrandService dtsBrandService;
@Autowired
public void setBrandService(DtsBrandService dtsBrandService) {
WebSocketServer.dtsBrandService = dtsBrandService;
}
@Autowired
public void setUserService(DtsUserService userService) {
WebSocketServer.dtsUserService = userService;
}