在Spring项目中,我使用了ServletContextListener
的监听器类型。我使用了 @Autowired
实例字段,但我无法在 contextInitialized(event)
方法中使用 Autowiring 实例变量,它会抛出 NullpointerException
.
如何使用@Autowired
来实现此目的
最佳答案
你不能。 @Autowired
仅在上下文初始化后才起作用。
所以你可以做这个黑客:
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");
}
}
或者更好的解决方案将感谢蜘蛛鲍里斯:
public class MyListener implements ServletContextListener {
@Autowired
private MyBean myBean;
@Override
public void contextInitialized(ServletContextEvent event) {
WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
ctx.autowireBean(this);
}
}
关于java - 如何在ServletContextListener中使用@Autowired实例变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39787519/