综合现有方案,总结如下:文章来源地址https://www.toymoban.com/news/detail-860285.html
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];
}
}
文章来源:https://www.toymoban.com/news/detail-860285.html
到了这里,关于SpringBoot如何获取当前运行环境,三种方式完美解决的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!