综合现有方案,有三种:
注解直接获取
配置Configuration
实现ApplicationContextAware
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获取当前运行环境三种方式
https://blog.51cto.com/u_3664660/3212705