Spring Boot 獲取上下文

新建獲取上下文工具類SpringContextUtil
package com.frank.lmsg.base.utils;

import org.springframework.context.ApplicationContext;

/**
 * Description: 獲取上下文工具類
 * Auth: Frank
 * Date: 2019-08-23
 * Time: 上午 10:44
 */
public class SpringContextUtil {
    private static ApplicationContext applicationContext;

    //獲取上下文
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //設(shè)置上下文
    public static void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextUtil.applicationContext = applicationContext;
    }

    //通過名字獲取上下文中的bean
    public static Object getBean(String name){
        return applicationContext.getBean(name);
    }

    //通過類型獲取上下文中的bean
    public static Object getBean(Class<?> requiredType){
        return applicationContext.getBean(requiredType);
    }


}

在Application里面初始化上下文
package com.frank.lmsg;

import com.frank.lmsg.base.utils.SpringContextUtil;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
@MapperScan("com.frank.lmsg.mybatis.mapper")
public class LmsgApplication {

    public static void main(String[] args) {
        ApplicationContext app = SpringApplication.run(LmsgApplication.class, args);
        SpringContextUtil.setApplicationContext(app);
    }

}

獲取上下文
    ApplicationContext app = SpringContextUtil.getApplicationContext();
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 在Spring中可以通過ContextLoader獲取上下文環(huán)境 但是這種方式在Spring Boot是失效的。本...
    AaronSimon閱讀 5,704評(píng)論 0 3
  • Swift1> Swift和OC的區(qū)別1.1> Swift沒有地址/指針的概念1.2> 泛型1.3> 類型嚴(yán)謹(jǐn) 對(duì)...
    cosWriter閱讀 11,632評(píng)論 1 32
  • 要想很好理解這個(gè)上下文的關(guān)系,需要先熟悉 spring 是怎樣在web容器中啟動(dòng)起來的。spring的啟動(dòng)過程其實(shí)...
    秋名山車神_f776閱讀 1,047評(píng)論 1 1
  • 經(jīng)歷了一個(gè)多小時(shí)的哭鬧,兩個(gè)孩子終于在車上睡著了。從北京開車到武漢不是第一次了,但大寶長(zhǎng)時(shí)間的哭鬧還是讓我出乎意...
    小渦魚閱讀 629評(píng)論 0 0
  • 目錄 隨著舞臺(tái)上表演的一支驚鴻舞,將整個(gè)歌舞表演推向了高潮。 一位身穿天藍(lán)色薄紗連身裙的妙齡女子,在舞臺(tái)中央翩翩舞...
    夏諾xn閱讀 574評(píng)論 10 17

友情鏈接更多精彩內(nèi)容