Spring Boot獲取spring.profiles.active:dev的值,也就是獲取當前運行的環境配置


這個spring.profiles.active的值雖然是可以通過@Value注解之類的方式獲取到,但如果需要獲取這個值的類是不被spring管理的呢?那就不能直接用過spring boot的簡單注解方式直接獲取值了,然后最近找到一個這個類。

復制代碼
@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext context = null;

    /* (non Javadoc)
     * @Title: setApplicationContext
     * @Description: spring獲取bean工具類
     * @param applicationContext
     * @throws BeansException
     * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        this.context = applicationContext;
    }

    // 傳入線程中
    public static <T> T getBean(String beanName) {
        return (T) context.getBean(beanName);
    }

    // 國際化使用
    public static String getMessage(String key) {
        return context.getMessage(key, null, Locale.getDefault());
    }

    /// 獲取當前環境
    public static String getActiveProfile() {
        return context.getEnvironment().getActiveProfiles()[0];
    }
}
復制代碼

可以在類加載完成后(也就是說需要注意使用的時間,這個結果是否正常返回了值)通過SpringContextUtil.getActiveProfile來獲取到spring.profiles.active=dev中的“dev”這個結果。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM