0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

SpringBoot ContextListenerクラス内でなぜかAutorewiredが機能しない時に実施した対処

Last updated at Posted at 2023-02-05

SpringBootでAutowiredがうまく機能せずとても困たので忘備録としてメモ。
@Autowiredで生成されるはずのBean(インスタンス)にアクセスすると何故かnullPointerExceptionが発生。
ContextListenerクラスのcontextInitializedメソッドの中でのみ発生した。他のクラスでは問題なくAutowiredを利用してBeanが生成されている状態。

原因は未だに分からないのだが、以下のようにServletContextクラスや、WebApplicationContextクラスを利用することでBeanを取得することができた。

以下のコードは上手くいかなかった例

...
import jp.co.com.sampleApplication.SampleField;
...

@WebListener
public class SampleApplicationContextListener implements ServletContextListener {

    //前提としてSampleFieldクラスには@Componentを付与している状態
    //SampleFieldクラスはgetSample()という簡単なゲッターを持っているとする
    @Autorwired
    SampleField sampelField;

    @Override
	public void contextInitialized(ServletContextEvent sce) {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);        
        //ゲッターgetSample()を呼び出すとnullPointerExceptionが発生してしまう
        sampleField.getSample();
    }


    @Override
	public void contextDestroyed(ServletContextEvent sce) {
        ...
        ...
	}
}

以下の記述だと問題なく処理が成功する

...
import jp.co.com.sampleApplication.SampleField;
...

@WebListener
public class SampleApplicationContextListener implements ServletContextListener {

    //@Autorwired
    //SampleField sampelField;

    @Override
	public void contextInitialized(ServletContextEvent sce) {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);

        //Context系のクラスを使用してBeanを取得する
        ServletContext context = sce.getServletContext();
        WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
        SampleField sampleField = wac.getBean(SampleField.class);
        
        //nullPointerExceptionにならない 
        sampleField.getSample();
    }


    @Override
	public void contextDestroyed(ServletContextEvent sce) {
        ...
        ...
	}
}

@Autowiredではダメだが、WebApplicationContextクラスを使用すればDIコンテナにあるBeanにアクセスできている模様?....なぜなのだろうか...。

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?