1

In Spring project, i used listener type of ServletContextListener. i have used instance field which is @Autowired, but i can't used autowired instance variable in contextInitialized(event) method, it throws NullpointerException.

How can use @Autowired for this

alex
  • 8,904
  • 6
  • 49
  • 75
  • 1
    You would have to wire it manually; Spring does not create the listener your Java EE server does. How do you create your `ApplicationContext`? Take a look at [this](http://stackoverflow.com/a/21914004/2071828). – Boris the Spider Sep 30 '16 at 08:58

2 Answers2

1

You can't. @Autowired works only after context is initialized.

So you can do this hack:

public class MyListener implements ServletContextListener {

    private MyBean myBean;    

    @Override
    public void contextInitialized(ServletContextEvent event) {
        WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
        this.myBean = (MyBean)ctx.getBean("myBean");
    }

}

or better solution would be thx to Boris the Spider:

public class MyListener implements ServletContextListener {

    @Autowired
    private MyBean myBean;    

    @Override
    public void contextInitialized(ServletContextEvent event) {
        WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
        ctx.autowireBean(this);
    }

}
alex
  • 8,904
  • 6
  • 49
  • 75
0

Well, Spring guarantees that it'll be initialized after the context initialization.

After it's initialized you can access it using:

MyClass myClass = ctx.getBean(MyClass.class);

In other words: you can't use @Autowired for making a contract which will force Spring to initialize your Bean before application context is finally initialized.

xenteros
  • 15,586
  • 12
  • 56
  • 91