来自 application.properties 的 Spring Boot 属性未在类@Configuration@



在 Spring-Boot 2.2.0 和 Java8 项目中。

我的应用程序中有一些属性-(profileActive(.properties(所以,在战争中(我想外部化为一个普通的配置文件(在战争之外(。这是因为这些属性每半年更改一次,将它们放在纯文本文件中会更方便(我可以使用 sed 命令等(。

可变属性文件的位置应在 application-(profileActive(.properties 中指定(它根据环境而更改(属性mutableproperties.project.root

我正在寻找一种解决方案,在整个项目中,所有@Value都像什么都没发生一样(重新启动后(继续工作。

我正在尝试使用以下类为一个文件加载这些属性:

@Configuration
public class MutableProperties {
@Value("${mutableproperties.project.root}")
private String mutablePropertiesRoot;
private String configFile(String type) {
StringBuffer file = new StringBuffer(mutablePropertiesRoot).append(File.pathSeparatorChar);
file.append(type).append(".properties");
return file.toString();
}
@Bean
public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurerDb() {
PropertySourcesPlaceholderConfigurer properties = new PropertySourcesPlaceholderConfigurer();
properties.setLocation(new FileSystemResource(configFile("db")));
properties.setIgnoreResourceNotFound(false);
return properties;
}
}

问题是 mutableRoot 为null(它在所有应用程序中 - (profileActive(.properties 中(为:

mutableproperties.project.root=/etc/properties/boot/myproject

我已经尝试过使用静态属性源占位器配置器,但它不适合,因为文件名实际上是动态的东西。

我对其他解决方案持开放态度来解决问题,但是JVM上的更改或跨许多类的操作并不合适。这必须是手术更改,可以在已经在生产环境中工作

我终于放弃了配置中的@Value。

解决方案是将属性放在 maven 配置文件中(因此,该属性不是硬编码的,而是在 pom 中(,让 maven 使用 org.codehaus.mojo.properties-maven-plugin 在此属性上设置的路径中创建一个属性文件。

有了这个:

  1. 我正在生成一个动态属性文件(在日食中找不到,只能在战争中找到(,由 maven 包含在战争中
  2. 其中有一个属性,可编辑属性文件所在的路径
  3. 从属性源占位符配置器我现在可以加载所有属性 是的,属性文件的名称是硬编码的,因为application.properties是,不是问题

私有静态最终字符串 FROMPOM_PROPERTIES_LOCATION = "/frompom.properties";

私有静态最终字符串 MUTABLES_ROOT_PROPERTY = "mutable.root";

private String mutablesLocation() throws ...{
Resource resource = new ClassPathResource("/frompom.properties");
return PropertiesLoaderUtils.loadProperties(resource).getProperty("mutable.root");
}
private PropertySourcesPlaceholderConfigurer configurer(String type) {
PropertySourcesPlaceholderConfigurer properties = new PropertySourcesPlaceholderConfigurer();
File file = new File("/" + mutablesLocation() + "mutable.properties");
properties.setLocation(new FileSystemResource(file));
return properties;
}
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>properties-maven-plugin</artifactId>
<version>1.0.0</version>
<executions>
<execution>
<phase>generate-resources</phase>
<goals>
<goal>write-project-properties</goal>
</goals>
<configuration>
<outputFile>${project.build.outputDirectory}frompom.properties</outputFile>
</configuration>
</execution>
</executions>
</plugin>

最新更新