1. 程式人生 > >Springboot中隨時獲取ApplicationContext,得到想要的bean

Springboot中隨時獲取ApplicationContext,得到想要的bean

在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);
}

建立工具類

package com.yssoft.fs.supervise.utils;

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); } }