spring的 onApplicationEvent方法被执行两次问题

原文地址:http://www.cnblogs.com/a757956132/p/5039438.html

 

在做web项目开发中,尤其是企业级应用开发的时候,往往会在工程启动的时候做许多的前置检查。

  比如检查是否使用了我们组禁止使用的Mysql的group_concat函数,如果使用了项目就不能启动,并指出哪个文件的xml文件使用了这个函数。

而在Spring的web项目中,我们可以介入Spring的启动过程。我们希望在Spring容器将所有的Bean都初始化完成之后,做一些操作,这个时候我们就可以实现一个接口:

复制代码
package com.yzg.listener;

@Component("StartupListener")//用注解就不需要在配置文件中添加注入
public class StartupListener implements ApplicationListener<ContextRefreshedEvent>{ @Override public void onApplicationEvent(ContextRefreshedEvent event) { //需要执行的逻辑代码,当spring容器初始化完成后就会执行该方法。 } }
复制代码

或者在在Spring的配置文件中,添加注入:

1 <bean class="com.yzg.listener.StartupListener"/>

但是这个时候,会存在一个问题,在web 项目中(spring mvc),系统会存在两个容器,一个是root application context ,另一个就是我们自己的 projectName-servlet  context(作为root application context的子容器)。

这种情况下,就会造成onApplicationEvent方法被执行两次。为了避免上面提到的问题,我们可以只在root application context初始化完成后调用逻辑代码,其他的容器的初始化完成,则不做任何处理,修改后代码

如下:

1 @Override
2   public void onApplicationEvent(ContextRefreshedEvent event) {
3       if(event.getApplicationContext().getParent() == null){//root application context 没有parent,他就是老大.
4            //需要执行的逻辑代码,当spring容器初始化完成后就会执行该方法。
5       }
6   }
posted @ 2017-01-20 16:38  蚂蚁1  阅读(13694)  评论(1编辑  收藏  举报