您的位置:首页 > 编程语言 > Java开发

spring容器加载完毕做一件事情(利用ContextRefreshedEvent事件)

2016-05-20 11:38 423 查看
  在开发时有时候需要在整个应用开始运行时执行一些特定代码,比如初始化环境,准备测试数据、加载一些数据到内存等等。

在Spring中可以通过ApplicationListener来实现相关的功能,加载完成后触发contextrefreshedevent事件(上下文件刷新事件)

 

Java代码  


<bean id="testContextRefreshedEvent" class="com.sf.sfbuy2.context.filter.TestContextRefreshedEvent"></bean>  

 

Java代码  


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初始化完成后调用逻辑代码,其他的容器的初始化完成,则不做任何处理,修改后代码

如下:

Java代码  


@Override  

  public void onApplicationEvent(ContextRefreshedEvent event) {  

      if(event.getApplicationContext().getParent() == null){//root application context 没有parent,他就是老大.  

           //需要执行的逻辑代码,当spring容器初始化完成后就会执行该方法。  

      }  

  }  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring