我有一节课:
package com.example.propertyorder;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
@SpringBootApplication
@PropertySource(value="file:C:\\TEMP\\property-order.properties", ignoreResourceNotFound = true)
public class PropertyOrderApplication {
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(PropertyOrderApplication.class, args);
Environment env = (Environment) run.getBean("environment");
System.out.println(env.getProperty("my.value"));
System.out.println(env.getProperty("my.value2"));
}
}我有一个application.properties文件:
my.value=application.properties我有我的外部属性文件C:\\TEMP\\property-order.properties
my.value=property-order.properties
my.value2=gotcha但结果总是:
application.properties
gotcha而不是:
property-order.properties
gotcha所以看起来,弹簧引导的application.properties凌驾于一切之上。有没有办法解决这个问题。我找到的唯一解决方案是不使用application.properties,而是使用一个my-app.properties,并将其放在ProperySource树中的外部文件之前:
@PropertySource(value="classpath:my-app.properties")
@PropertySource(value="file:C:\\TEMP\\property-order.properties", ignoreResourceNotFound = true)有更好的方法吗?这样我就可以和application.properties待在一起了?
编辑:
将缺失的value2添加到属性文件中
发布于 2018-07-06 13:16:31
实际行为符合弹簧启动文件:
Spring使用了一个非常特殊的PropertySource顺序,旨在允许合理地重写值。对属性的考虑顺序如下: …… 14.打包jar之外的应用程序属性(application.properties和YAML变体)。 15. jar中打包的应用程序属性(application.properties和YAML变体)。 16.@PropertySource注释在您的@Configuration类上。
与添加在application.properties类(16)中的任何@PropertySource注释相比,jar(jar内部或外部)具有更高的优先级(分别为14和15 )。
有更好的方法吗?这样我就可以和application.properties待在一起了?
当然,您可以使用13种更高优先级的方法中的任何一种:
1.主目录上的devtools全局设置属性(当devtools处于活动状态时,~/. settings devtools.properties)。 2.@TestPropertySource对测试的注释。 测试中的3.@SpringBootTest#properties注释属性。命令行参数。 4.来自SPRING_APPLICATION_JSON的属性(嵌入在环境变量或系统属性中的内联JSON )。 5.ServletConfig init参数。 6.ServletContext init参数。 7. java:comp/env中的JNDI属性。 8.Java属性(System.getProperties())。 9.操作系统环境变量。 10.只具有随机属性的RandomValuePropertySource。 11.在打包jar (应用程序-{profile}.properties和YAML变体)之外的特定于配置文件的应用程序属性。 12. jar中打包的特定于配置文件的应用程序属性( application -{profile}.properties和YAML变体)。 13.打包jar之外的应用程序属性(application.properties和YAML变体)。
例如,将property-order.properties重命名为application-order.properties,使其成为Spring属性,并以order作为活动配置文件运行应用程序将赋予它更高的优先级,因此应该足够了:
@SpringBootApplication
public class PropertyOrderApplication {...}发布于 2018-07-06 13:18:43
如果要覆盖在application.properties中定义的属性,可以使用以下方法。
@PropertySources({
@PropertySource(value = "classpath:application.properties"),
@PropertySource(value = "file:/user/home/external.properties", ignoreResourceNotFound = true)
})
public class Application {
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
}
}https://stackoverflow.com/questions/51211054
复制相似问题