在springboot主程序里改成
public static void main(String[] args) {// SpringApplication.run(SpringbootAPP.class, args);换成下面 SpringApplication sa = new SpringApplication(SpringbootAPP.class); sa.addListeners(new MainBusiListeners()); sa.run(args);}
package com.xxx.xxxx;import com.xxx.utils.SpringContextUtils;import org.springframework.context.ApplicationListener;import org.springframework.context.event.ContextRefreshedEvent;/** * 启动监听 */public class MainBusiListeners implements ApplicationListener{ @Override public void onApplicationEvent(ContextRefreshedEvent event) { SpringContextUtils.setApplicationContextByMain(event.getApplicationContext()); }}
@Componentpublic class SpringContextUtils { private static ApplicationContext applicationContext; public static void setApplicationContextByMain(ApplicationContext applicationContext) { if (SpringContextUtils.applicationContext == null) { SpringContextUtils.applicationContext = applicationContext; } }
参考文章: