springboot获取上下文ApplicationContext
在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<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { SpringContextUtils.setApplicationContextByMain(event.getApplicationContext()); } }
@Component public class SpringContextUtils { private static ApplicationContext applicationContext; public static void setApplicationContextByMain(ApplicationContext applicationContext) { if (SpringContextUtils.applicationContext == null) { SpringContextUtils.applicationContext = applicationContext; } }