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));

猜你喜欢

转载自blog.csdn.net/qq_41070393/article/details/123950153