Spring - 将依赖项注入ServletContextListener

dog*_*ane 27 java spring tomcat servlets dependency-injection

我想将一个依赖注入一个ServletContextListener.但是,我的方法不起作用.我可以看到Spring正在调用我的setter方法,但是稍后在contextInitialized调用时,属性是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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

<listener>
  <listener-class>MyListener</listener-class>
</listener> 
Run Code Online (Sandbox Code Playgroud)

applicationContext.xml中:

<bean id="listener" class="MyListener">
  <property name="prop" value="HELLO" />
</bean>  
Run Code Online (Sandbox Code Playgroud)

输出:

set prop to HELLO
Initialising listener...
null
Run Code Online (Sandbox Code Playgroud)

实现这一目标的正确方法是什么?

a.b*_*b.d 30

dogbane的答案(已接受)有效,但由于bean的实例化方式,它使测试变得困难.我更喜欢这个问题中提出的方法:

@Autowired private Properties props;

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

    //Do something with props
    ...
}    
Run Code Online (Sandbox Code Playgroud)

  • 我知道这是旧的,但对于未来的读者,当我尝试这个时,我得到一个`IllegalStateException`,带有消息*没有找到WebApplicationContext:没有注册ContextLoaderListener?* (3认同)

dog*_*ane 17

我通过删除监听器bean并为我的属性创建一个新bean来解决这个问题.然后我在我的监听器中使用以下内容来获取属性bean:

@Override
public void contextInitialized(ServletContextEvent event) {

    final WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
    final Properties props = (Properties)springContext.getBean("myProps");
}
Run Code Online (Sandbox Code Playgroud)


Ric*_*coZ 5

如前所述,ServletContextListener是由服务器创建的,因此它不受spring管理.

如果您希望收到ServletContext的通知,可以实现该接口:

org.springframework.web.context.ServletContextAware
Run Code Online (Sandbox Code Playgroud)