ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] # 简介 在springboot中有一种实现方式,可以很方便的获取到ApplicationContext对象:SpringBoot平台下采用ApplicationContextAware的方式完成ApplicationContext实例的获取,并通过ApplicationContext实例完成对Spring管理的Bean实例手动获取。 创建一个实体类SpringUtil并实现ApplicationContextAware接口,重写接口内的setApplicationContext方法来完成获取ApplicationContext实例的方法。 如下为ApplicationContextAware接口: ~~~ public interface ApplicationContextAware extends Aware { void setApplicationContext(ApplicationContext var1) throws BeansException; } ~~~ 注意两个地方: 1. SpringUtil类上的 @Component注解必须要有,否则spring就不会自动调用setApplicationContext方法来为我们设置上下文实例; 2. SpringUtil类要在springboot可以扫描到的包下; # 实现 在springBoot启动类的main方法中写成 ~~~ /** * 启动嵌入式的Tomcat并初始化Spring环境 */ public static void main(String[] args) throws Exception { ApplicationContext app = SpringApplication.run(WebApplication.class, args); SpringUtil.setApplicationContext(app); //SpringApplication.run(WebApplication.class, args); } ~~~ 创建工具类 ~~~ import com.yssoft.fs.repository.entity.comm.EarlyWarningTask; import com.yssoft.fs.supervise.service.riskWarning.RiskWarningTaskService; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import javax.annotation.Resource; import java.util.List; public class SpringUtil { private static ApplicationContext applicationContext = null; // 非@import显式注入,@Component是必须的,且该类必须与main同包或子包 // 若非同包或子包,则需手动import 注入,有没有@Component都一样 // 可复制到Test同包测试 public static void setApplicationContext(ApplicationContext applicationContext) throws BeansException { if(SpringUtil.applicationContext == null){ SpringUtil.applicationContext = applicationContext; } //查询所有预警任务,开启的预警任务自动开启 RiskWarningTaskService riskWarningTaskServiceStatic=applicationContext.getBean(RiskWarningTaskService.class); List<EarlyWarningTask> earlyWarningTask = riskWarningTaskServiceStatic.findEarlyWarningTaskAll(); for (EarlyWarningTask warningTask : earlyWarningTask) { //如果任务是打开的,可就开启任务 if("1".equals(warningTask.getStat())){ riskWarningTaskServiceStatic.editState("1",warningTask.getId().toString(),warningTask.getTitle()); riskWarningTaskServiceStatic.editState("0",warningTask.getId().toString(),warningTask.getTitle()); } } } //获取applicationContext public static ApplicationContext getApplicationContext() { return applicationContext; } //通过name获取 Bean. public static Object getBean(String name){ return getApplicationContext().getBean(name); } //通过class获取Bean. public static <T> T getBean(Class<T> clazz){ return getApplicationContext().getBean(clazz); } //通过name,以及Clazz返回指定的Bean public static <T> T getBean(String name,Class<T> clazz){ return getApplicationContext().getBean(name, clazz); } } ~~~