spring boot2.5x、2.6x获取环境变量(spring.profiles.active),获取classpath下文件方法

背景

升级spring boot版本后,发现原来使用@Value注解获取环境提示异常

旧版本环境设置

spring:
  profiles:
    active: dev

新版本环境变量设置变了

spring:
  config:
    activate:
      on-profile: dev

当需要环境工具类获取环境时就读取不到

解决办法

通过注入Environment environment获取

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicReference;

@Component
public class EnvUtils {

    @Autowired
    private Environment environment;
    private final AtomicReference<String> env = new AtomicReference<>();
    private final AtomicReference<String> databaseName = new AtomicReference<>();

    private void init() {
    	// 初始化环境
        initEnv();
        // 初始化自定义属性
        initDatabaseName();
    }

    private void initEnv() {
        if (env.get() != null) {
            return;
        }

        env.set(environment.getActiveProfiles()[0]);
    }

    private void initDatabaseName() {
        if (databaseName.get() != null) {
            return;
        }

        databaseName.set(environment.getProperty("spring.datasource.clickhouse.database"));
    }

    public boolean isPro() {
        init();
        return "pro".equals(env.get());
    }

    public boolean notPro() {
        return !isPro();
    }
}

题外话

java程序启动时指定参数

  • java -jar -Dspring.profiles.active=dev
  • Dockerfile文件写死-Dspring.profiles.active=dev
    这样可以解决问题,但觉得麻烦

获取classpath下的文件

例如:项目resource下存在文件a.txt
获取代码

// 获取文件
File file = org.springframework.util.ResourceUtils.getFile("classpath:a.txt");

// 得到文件后续操作..略
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值