当spring 容器初始化完成后执行某个方法 防止onApplicationEvent方法被执行两次

来源:互联网 发布:淘宝上碧欧泉是正品吗 编辑:程序博客网 时间:2024/05/21 10:52

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

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

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

package com.yk.test.executor.processorpublic class InstantiationTracingBeanPostProcessor implements ApplicationListener<ContextRefreshedEvent> {    @Override    public void onApplicationEvent(ContextRefreshedEvent event) {      //需要执行的逻辑代码,当spring容器初始化完成后就会执行该方法。 }}

同时在Spring的配置文件中,添加注入:

<bean class="com.yk.test.executor.processor.InstantiationTracingBeanPostProcessor"/>

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

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

如下:

@Overridepublic void onApplicationEvent(ContextRefreshedEvent event) {       if(event.getApplicationContext().getParent() == null){//root application context 没有parent,他就是老大.            //需要执行的逻辑代码,当spring容器初始化完成后就会执行该方法。       }}



0 0
原创粉丝点击