0
1

More than 3 years have passed since last update.

Spring Boot で TextWebSocketHandler を継承したクラスで Autowired したフィールドが NULL になる

Posted at

1.環境

Spring Boot:v2.2.5

2.困ったこと

Spring Boot でチャット機能を作成するため、WebSocket を利用。

TextWebSocketHandler を継承したクラスを作成し、その中で DB にアクセスするためにリポジトリクラスを Autowired しようとしたが、フィールドに宣言したリポジトリクラスの変数が NULL。

以下が TextWebSocketHandler を継承した WebSocketChatEndpoint クラス。

WebSocketChatEndpoint.java
@ServerEndpoint("/api/chat")
@Component
public class WebSocketChatEndpoint extends TextWebSocketHandler {

  @Autowired
  private ChatRepository chatRepository; //NULL

  @OnOpen
  public void onOpen(Session session) {
  

実行時、chatRepository が NULL。

3.対応

フィールドインジェクションをセッターインジェクションに変更。

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) {
  

コンストラクタインジェクションは試してません。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1