springboot优雅的获取当前环境类型,优雅的获取application.properties中的值
程序员文章站
2022-05-02 11:41:43
...
楼主因为这个简单 的获取当前环境变量踩坑,故作
话不多说直接上代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
//Component 让spring容器扫描到
@Component
public class TestUtil {
//标注为静态变量
//对效率 放在堆中不费时
//对使用 不需要频繁注入@Value
//故优雅。
public static String thisSystemParam;
//注入 spring启动时即加载赋值
@Autowired
public void setThisSystemParam(@Value("${spring.profiles.active}")String thisSystemParam) {
TestUtil.thisSystemParam = thisSystemParam;
}
}
网上有关于获取的是这段
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
if(SpringContextUtil.applicationContext == null) {
SpringContextUtil.applicationContext = applicationContext;
}
}
//该方法会有大概率为Null 建议不使用
public static String getActiveProfile() {
return applicationContext.getEnvironment().getActiveProfiles()[0];
}
}
另 有好的方式或者方法可留言评论,一起探讨。希望本文可以帮到你
上一篇: 开发不常用点总结