Spring Boot中从激活配置文件读写配置值的问题
问题描述
我在application-dev和application-qa配置文件中存储了一些配置值,希望根据当前激活的配置文件修改对应配置。现有代码固定操作application-dev.properties,代码如下:
Properties props = new Properties(); InputStream input = null; OutputStream output = null; try { input = new FileInputStream("src\\main\\resources\\application-dev.properties"); props.load(input); props.setProperty(key, value); output = new FileOutputStream("src\\main\\resources\\application-dev.properties"); props.store(output, null); } catch(IOException ex) { ex.printStackTrace(); }
我了解@Profile注解可识别激活配置,但无法成功获取当前激活配置文件的值,请问该如何解决?
解决方案
方法1:通过Spring环境变量获取激活的配置文件
Spring启动后会将激活的配置文件信息存入环境变量,直接注入Environment对象就能获取当前激活的profile:
import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @Component public class ConfigEditor { private final Environment environment; // 构造注入Environment public ConfigEditor(Environment environment) { this.environment = environment; } public void updateConfig(String key, String value) { // 获取当前激活的所有profile,取第一个即可(通常单profile激活) String[] activeProfiles = environment.getActiveProfiles(); if (activeProfiles.length == 0) { // 无激活profile时,默认使用dev,可根据业务调整 activeProfiles = new String[]{"dev"}; } String activeProfile = activeProfiles[0]; // 拼接目标配置文件路径 String configPath = "src\\main\\resources\\application-" + activeProfile + ".properties"; Properties props = new Properties(); // 用try-with-resources自动关闭流,避免资源泄漏 try (InputStream input = new FileInputStream(configPath); OutputStream output = new FileOutputStream(configPath)) { props.load(input); props.setProperty(key, value); props.store(output, null); } catch(IOException ex) { ex.printStackTrace(); } } }
方法2:通过@Value直接注入激活的profile名称
也可以用@Value注解直接获取激活的profile名称,写法更简洁:
import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; @Component public class ConfigEditor { // 未指定激活profile时,默认用dev @Value("${spring.profiles.active:dev}") private String activeProfile; public void updateConfig(String key, String value) { String configPath = "src\\main\\resources\\application-" + activeProfile + ".properties"; // 后续文件操作同方法1,此处省略重复代码 } }
关键注意点
- 确保你的类被Spring容器管理(添加
@Component或同类注解),否则无法注入Environment或使用@Value - 多profile激活场景下,需根据业务逻辑选择要修改的目标配置文件
- 优先使用try-with-resources语法处理流,避免手动关闭时遗漏导致的资源泄漏
内容的提问来源于stack exchange,提问作者user21234637
相关产品推荐
相关产品推荐

