Autowired fields in a class that inherits TextWebSocketHandler in Spring Boot become NULL

1. Environment

Spring Boot:v2.2.5

2. Trouble

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.

3. Correspondence

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

Autowired fields in a class that inherits TextWebSocketHandler in Spring Boot become NULL
What is @Autowired in Spring boot?
A memo that touched Spring Boot
[Spring Boot] Until @Autowired is run in the test class [JUnit5]
A story about a Spring Boot project written in Java that supports Kotlin
Run a Spring Boot project in VS Code
How to create a class that inherits class information
How to add a classpath in Spring Boot
Get the path defined in Controller class of Spring boot as a list
Java tips-Create a Spring Boot project in Gradle
Write a class that can be ordered in Java
How to create a Spring Boot project in IntelliJ
Test field-injected class in Spring boot test without using Spring container
Accelerate testing of Validators that require DI in Spring Boot
Sample web application that handles multiple databases in Spring Boot 1.5
[MQTT / Java] Implemented a class that does MQTT Pub / Sub in Java
Set context-param in Spring Boot
Spring Boot 2 multi-project in Gradle
Major changes in Spring Boot 1.5
NoHttpResponseException in Spring Boot + WireMock
RSocket is supported in Spring Boot 2.2, so give it a try
Sample code that uses the Mustache template engine in Spring Boot
Get a proxy instance of the component itself in Spring Boot
[Spring Boot] Mock the contents that are autowired outside the scope [JUnit 5]
Fitted in Spring Boot using a bean definition file named application.xml
Let's write a test code for login function in Spring Boot