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

spring启动自动后执行特定方法

2017-07-06 15:53 453 查看
在做web项目开发中,尤其是企业级应用开发的时候,往往会在工程启动的时候做许多的前置检查或者去执行某些方法。而在Spring的web项目中,可以介入Spring的启动过程。在Spring容器将所有的Bean都初始化完成之后,做一些操作,这个时候我们就可以实现一个接口:

package com.wangru.selfStart;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

public class InstantiationTracingBeanPostProcessor implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if(event.getApplicationContext().getParent() == null){//root application context 没有parent,他就是老大.
System.out.println("开机自启动------------开机自启动-------开机自启动-------开机自启动");
}
}
}


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

<bean class="com.wangru.selfStart.InstantiationTracingBeanPostProcessor"/>


这样,在工程启动的时候就会自动启动onApplicationEvent方法,实现业务需求。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息