`

转: 当spring 容器初始化完成后执行某个方法

 
阅读更多
转自: http://www.cnblogs.com/rollenholt/p/3612440.html


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

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

而在Spring的web项目中,我们可以介入Spring的启动过程。我们希望在Spring容器将所有的Bean都初始化完成之后,做一些操作,这个时候我们就可以实现一个接口:
	
package com.yk.test.executor.processor
public class InstantiationTracingBeanPostProcessor implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
      //需要执行的逻辑代码,当spring容器初始化完成后就会执行该方法。
 }
}


同时在Spring的配置文件中,添加注入:
	
<!--      当Spring容器启动完成后执行下面的这个Bean -->
    <bean class="com.yk.test.executor.processor.InstantiationTracingBeanPostProcessor"/>

  
但是这个时候,会存在一个问题,在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容器初始化完成后就会执行该方法。
      }
  }

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics