Spring Boot:v2.2.5
Use WebSocket to create a chat function with Spring Boot.
I created a class that inherits from TextWebSocketHandler and tried to Autowired the repository class to access the DB in it, but the repository class variable declared in the field is NULL.
The following is the WebSocketChatEndpoint class that inherits from TextWebSocketHandler.
WebSocketChatEndpoint.java
@ServerEndpoint("/api/chat")
@Component
public class WebSocketChatEndpoint extends TextWebSocketHandler {
@Autowired
private ChatRepository chatRepository; //NULL
@OnOpen
public void onOpen(Session session) {
… Abbreviation
At run time, chatRepository is NULL.
Changed field injection to setter injection.
WebSocketChatEndpoint.java
@ServerEndpoint("/api/chat")
@Component
public class WebSocketChatEndpoint extends TextWebSocketHandler {
private static ChatRepository chatRepository; //Autowired
@Autowired
public void setChatRepository (ChatRepository chatRepository ) {
WebSocketChatEndpoint.chatRepository = chatRepository;
}
@OnOpen
public void onOpen(Session session) {
… Abbreviation
I haven't tried constructor injection.
Recommended Posts