SpringBoot获取当前运行环境三种方式小结
更新时间:2024年01月29日 10:58:12 作者:BigManing
在使用SpringBoot过程中,我们只需要引入相关依赖,然后在main方法中调用SpringBootApplication.run(应用程序启动类.class)方法即可,那么SpringBoot是如何获取当前运行环境呢,接下来由小编给大家介绍一下SpringBoot获取当前运行环境三种方式,需要的朋友可以参考下
一个项目中出现多个环境的配置文件

在代码里我们可以通过下面的方法获取当前的环境。
综合现有方案,总结如下:
1、注解直接获取
@Value("${spring.profiles.active}")
private String env;
2、配置Configuration
@Configuration
public class ProfileConfig {
@Autowired
private ApplicationContext context;
public String getActiveProfile() {
return context.getEnvironment().getActiveProfiles()[0];
}
}
3、实现ApplicationContextAware
@Component
public class SpringUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
if (SpringUtils.applicationContext == null) {
SpringUtils.applicationContext = applicationContext;
}
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
public static <T> T getBean(Class<T> clazz) {
return getApplicationContext().getBean(clazz);
}
public static <T> T getBean(String name, Class<T> clazz) {
return getApplicationContext().getBean(name, clazz);
}
/**
* 获取当前环境
*/
public static String getActiveProfile() {
return context.getEnvironment().getActiveProfiles()[0];
}
}
小结
到此这篇关于SpringBoot获取当前运行环境三种方式小结的文章就介绍到这了,更多相关SpringBoot获取当前运行环境内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
Spring Data JPA系列JpaSpecificationExecutor用法详解
这篇文章主要为大家介绍了Spring Data JPA系列JpaSpecificationExecutor用法详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-09-09
SpringMVC对自定义controller入参预处理方式
这篇文章主要介绍了SpringMVC对自定义controller入参预处理方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-09-09
java并发编程工具类JUC之ArrayBlockingQueue
类ArrayBlockingQueue是BlockingQueue接口的实现类,它是有界的阻塞队列,内部使用数组存储队列元素,通过代码给大家说明如何初始化一个ArrayBlockingQueue,并向其中添加一个对象,对java并发编程工具类ArrayBlockingQueue相关知识感兴趣的朋友一起看看吧2021-05-05


最新评论