小编典典

如何在应用程序上下文初始化事件中添加一个侦听器?

spring

对于常规的Servlet,我想你可以声明一个上下文侦听器,但是对于Spring MVC,Spring可以使它更容易吗?

此外,如果定义了上下文侦听器,然后需要访问在servlet.xml或中定义的bean,我applicationContext.xml将如何访问它们?


阅读 543

收藏
2020-04-11

共1个答案

小编典典

为此,你必须创建并注册一个实现该ApplicationListener接口的bean,如下所示:

package test.pack.age;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

public class ApplicationListenerBean implements ApplicationListener {

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ContextRefreshedEvent) {
            ApplicationContext applicationContext = ((ContextRefreshedEvent) event).getApplicationContext();
            // now you can do applicationContext.getBean(...)
            // ...
        }
    }
}

然后,你在servlet.xmlapplicationContext.xml文件中注册此bean :

<bean id="eventListenerBean" class="test.pack.age.ApplicationListenerBean" />

当应用程序上下文初始化时,Spring会通知它。

在Spring 3中(如果使用的是该版本),ApplicationListener该类是通用的,你可以声明你感兴趣的事件类型,并且事件将被相应地过滤。你可以像下面这样简化你的bean代码:

public class ApplicationListenerBean implements ApplicationListener<ContextRefreshedEvent> {

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext applicationContext = event.getApplicationContext();
        // now you can do applicationContext.getBean(...)
        // ...
    }
}
2020-04-11