Java 如何在ServletContextListener中使用@Autowired实例变量use
在Spring项目中,我使用了监听器类型Java 如何在ServletContextListener中使用@Autowired实例变量use,java,spring,Java,Spring,在Spring项目中,我使用了监听器类型ServletContextListener。我使用了实例字段,它是@Autowired,但我不能在contextInitialized(event)方法中使用Autowired实例变量,它抛出NullpointerException 如何使用@Autowired实现这一点好吧,Spring保证它将在上下文初始化之后初始化 初始化后,您可以使用以下方式访问它: MyClass myClass = ctx.getBean(MyClass.class); 换
ServletContextListener
。我使用了实例字段,它是@Autowired
,但我不能在contextInitialized(event)
方法中使用Autowired实例变量,它抛出NullpointerException
如何使用
@Autowired
实现这一点好吧,Spring保证它将在上下文初始化之后初始化
初始化后,您可以使用以下方式访问它:
MyClass myClass = ctx.getBean(MyClass.class);
换句话说:您不能使用
@Autowired
来创建一个契约,该契约将强制Spring在应用程序上下文最终初始化之前初始化您的Bean
。您不能<代码>@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");
}
}
或者更好的解决方案是对蜘蛛Boris的thx:
您必须手动连接它;Spring不会创建JavaEE服务器所创建的侦听器。如何创建
应用程序上下文
?看一看。
public class MyListener implements ServletContextListener {
@Autowired
private MyBean myBean;
@Override
public void contextInitialized(ServletContextEvent event) {
WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
ctx.autowireBean(this);
}
}