小编典典

Spring-将依赖项注入ServletContextListener

spring

我想将依赖项注入ServletContextListener。但是,我的方法不起作用。我可以看到Spring正在调用我的setter方法,但是稍后在contextInitialized调用when时,该属性为null

这是我的设置:

ServletContextListener:

public class MyListener implements ServletContextListener{

    private String prop;

    /* (non-Javadoc)
     * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
     */
    @Override
    public void contextInitialized(ServletContextEvent event) {
        System.out.println("Initialising listener...");
        System.out.println(prop);
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
    }

    public void setProp(String val) {
        System.out.println("set prop to " + prop);
        prop = val;
    }
}

web.xml :(这是文件中的最后一个侦听器)

<listener>
  <listener-class>MyListener</listener-class>
</listener> 
applicationContext.xml:

<bean id="listener" class="MyListener">
  <property name="prop" value="HELLO" />
</bean>  

输出:

set prop to HELLO
Initialising listener...
null

实现此目的的正确方法是什么?


阅读 506

收藏
2020-04-13

共1个答案

小编典典

Dogbane的答案(已接受)有效,但是由于实例化bean的方式,这使测试变得困难。我更喜欢此问题中建议的方法:

@Autowired private Properties props;

@Override
public void contextInitialized(ServletContextEvent sce) {
    WebApplicationContextUtils
        .getRequiredWebApplicationContext(sce.getServletContext())
        .getAutowireCapableBeanFactory()
        .autowireBean(this);

    //Do something with props
    ...
}   
2020-04-13