這個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”這個結果。