这个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”这个结果。

