在开发时有时候需要在整个应用开始运行时执行一些特定代码,比如初始化环境,准备测试数据、加载一些数据到内存等等。
在Spring中可以通过ApplicationListener来实现相关的功能,加载完成后触发contextrefreshedevent事件(上下文件刷新事件)
- <bean id="testContextRefreshedEvent" class="com.sf.sfbuy2.context.filter.TestContextRefreshedEvent"></bean>
- import org.springframework.context.ApplicationListener;
- import org.springframework.context.event.ContextRefreshedEvent;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- public class TestContextRefreshedEvent implements ApplicationListener<ContextRefreshedEvent>{
- @Override
- public void onApplicationEvent(ContextRefreshedEvent arg0) {
- System.out.println("Spring容器加载完成触发,可用于初始化环境,准备测试数据、加载一些数据到内存");
- }
- public static void main(String[] args) {
- ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
- context.close();
- }
- }
但是这个时候,会存在一个问题,在web 项目中(spring mvc),系统会存在两个容器,一个是root application context ,另一个就是我们自己的 projectName-servlet context(作为root application context的子容器)。
这种情况下,就会造成onApplicationEvent方法被执行两次。为了避免上面提到的问题,我们可以只在root application context初始化完成后调用逻辑代码,其他的容器的初始化完成,则不做任何处理,修改后代码
如下:
- @Override
- public void onApplicationEvent(ContextRefreshedEvent event) {
- if(event.getApplicationContext().getParent() == null){//root application context 没有parent,他就是老大.
- //需要执行的逻辑代码,当spring容器初始化完成后就会执行该方法。
- }
- }
参考:http://blog.csdn.net/u013400939/article/details/51460491
ApplicationContext在运行期会自动检测到所有实现了ApplicationListener的bean对象,并将其作为事件接收对象。当ApplicationContext的publishEvent方法被触发时,每个实现了ApplicationListener接口的bean都会收到ApplicationEvent对象,每个ApplicationListener可根据事件类型只接收处理自己感兴趣的事件,比如上面的StudentAddListener只接收StudentAddEvent事件。
http://blog.csdn.net/liuwenbo0920/article/details/7263766(非常好)
http://yangyongbyjava.iteye.com/blog/1600581
http://www.th7.cn/Program/java/201408/271385.shtml(ApplicationListener接口中的onApplicationEvent被调用两次解决方案)
Spring监听 ApplicationListener