SpringBoot获取当前运行环境三种方式

综合现有方案,有三种:

  1. 注解直接获取
  2. 配置Configuration
  3. 实现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];
    }
}

 

### 获取Spring Boot应用程序中当前激活的Profile 在Spring Boot应用中,有几种不同的方式可以获取当前激活的Profile: #### 使用`Environment`对象 通过注入`org.springframework.core.env.Environment`接口来访问活动配置文件的信息。这允许程序动态地读取并响应不同环境下设置的不同属性。 ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; public class ProfileService { @Autowired private Environment env; public String getCurrentActiveProfiles() { return Arrays.toString(env.getActiveProfiles()); } } ``` 此代码片段展示了如何创建一个服务类来返回所有活跃的配置文件名称列表[^1]。 #### 静态获取方式 对于某些场景下可能不需要依赖于Spring容器自动装配机制,则可以直接利用静态上下文工具类实现同样的功能。需要注意的是这种方法通常用于非常特殊的情况下,在大多数情况下推荐使用上述基于依赖注入的方法。 ```java import org.springframework.context.ApplicationContextInitializer; import org.springframework.web.context.WebApplicationContext; public final class ApplicationContextHelper { private static WebApplicationContext context; // ...其他初始化逻辑... /** * Get active profiles. */ public static String[] getActiveProfiles(){ return context.getEnvironment().getActiveProfiles(); } } ``` 这段代码定义了一个辅助器用来保存全局的应用上下文实例,并提供了获取当前激活配置文件名数组的方法[^3]。 #### 控制台输出查看 当运行Spring Boot应用程序时,默认会在日志信息里打印出已加载的配置文件详情。如果只是简单确认哪个profile被激活而无需编程手段的话,可以在控制台上查找类似下面的日志条目: ``` The following profiles are active: dev, test ``` 这种方式适用于快速验证目的而不必修改任何源码[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值