Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sql-server-2005/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在ServletContextListener中使用@Autowired实例变量use_Java_Spring - Fatal编程技术网

Java 如何在ServletContextListener中使用@Autowired实例变量use

Java 如何在ServletContextListener中使用@Autowired实例变量use,java,spring,Java,Spring,在Spring项目中,我使用了监听器类型ServletContextListener。我使用了实例字段,它是@Autowired,但我不能在contextInitialized(event)方法中使用Autowired实例变量,它抛出NullpointerException 如何使用@Autowired实现这一点好吧,Spring保证它将在上下文初始化之后初始化 初始化后,您可以使用以下方式访问它: MyClass myClass = ctx.getBean(MyClass.class); 换

在Spring项目中,我使用了监听器类型
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);
    }

}