日期:2014-05-17  浏览次数:20716 次

如何在区分spring的IOC容器和spring MVC的IOC容器的ContextRefreshedEvent?
现在需要监听IOC容器的加载完毕事件,继承了ApplicationListener,对ApplicationEvent的类型进行判断,如果是ContextRefreshedEvent就说明加载完毕。

但是实际使用时发现,项目中如果使用了Spring MVC,ContextRefreshedEvent会触发2次,1次是ApplicationContext.xml初始化完毕时,一次是mvc的IOC初始化容器完毕时,请问如何区分这2个事件?

------解决方案--------------------
这两个不好区分 。 它确实会出发两次ContextRefreshedEvent事件,如果你想监听的方法不要重复执行两次 ,可以用一个boolean变量来控制 , 如下:
Java code

@Component
public class StartUpListener implements ApplicationListener<ApplicationEvent>{
    public static boolean isStart = false;
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if(isStart)
            return ;
        System.err.println("容器启动............");
        isStart = true ;
    }
}