1. 程式人生 > 其它 >spring boot 獲取執行時的yml裡的active配置

spring boot 獲取執行時的yml裡的active配置

@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];
    }
}