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

xiaoxiao2021-02-28  7

在做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方法,实现业务需求。

转载请注明原文地址: https://www.6miu.com/read-1150217.html

最新回复(0)