Spring @PropertySources值不会覆盖

时间:2017-02-20 07:58:15

标签: java spring spring-mvc spring-boot

我将Spring Boot应用程序部署为Tomcat中的WAR文件。我期待我的application-local.properties覆盖我的application.properties文件中也存在的值。但似乎只有在application.properties中不存在这些键时才会读取application-local.properties中的值。我的application.properties文件位于我的项目的src / main / resources /中,application-local.properties位于$ {catalina.home} / property_files / com / demo / config文件夹中

context.xml中

<Parameter name="spring.profiles.active" value="local" override="false"/>

catalina.properties

shared.loader=${catalina.home}/property_files

AppConfig.java

@Configuration
@PropertySources({
    @PropertySource("classpath:application.properties"),
    @PropertySource("classpath:com/demo/config/application-${spring.profiles.active}.properties")
})
public class AppConfig extends WebMvcConfigurerAdapter {
}

编辑1:实际上,正在加载我的依赖于环境的属性文件。但它不会覆盖内部属性文件中的任何值。

编辑2:感谢你的所有建议。但我发现我的问题是由目录优先级引起的。事实证明,根类路径上的属性文件的优先级高于任何属性文件,无论它们的声明顺序如何。

6 个答案:

答案 0 :(得分:3)

  

在启动时尝试设置,而不是使用许多propertySource注释   应用

java -jar myproject.jar --spring.config.location = {your_location} /application.properties,classpath:/override.properties。

  

作为命令行的一部分,您提供的内容将是最高的   优先。
  或做这样的事情并测试

@Configuration
@PropertySource("classpath:application.properties")
public class DefaultConfiguration {}
@Configuration
@PropertySource("classpath:{environment_specific_property_name}.properties")
public class EnvironmentSpecific{

    @Configuration
    @Import(DefaultConfiguration .class)
    static class Configuration {}

}

答案 1 :(得分:1)

你可以使用:

table

如果文件实际位于指定的位置并且将获得所需的值,这应该有效。

答案 2 :(得分:1)

而不是application.properties,将您的默认配置/属性放在不同的文件中。似乎application.properties中定义的属性值具有最高优先级。

所以,这样的事情会奏效:

config/initializers/backtrace_silencers.rb

在Spring 4.x和Java 8中测试

答案 3 :(得分:0)

应该是:

@Configuration
@PropertySources({
    @PropertySource("classpath:application.properties"),
    @PropertySource("file:${catalina.home}/property_files/com/demo/config/application-${spring.profiles.active}.properties")
})
public class AppConfig extends WebMvcConfigurerAdapter {
}

未测试

答案 4 :(得分:0)

您可以使用此配置覆盖类路径中application.properties的属性,并使用外部application.properties文件, 忽略后面的如果没有这样的文件,请注意order参数,如果有多个文件,你可以设置优先顺序。

<!--load from external file first-->
<context:property-placeholder order="1" ignore-resource-not-found="true" 
        location="file:/path_to/your_app/application.properties" ignore-unresolvable="true"/>
<!--load any properties not found in file from class path-->
<context:property-placeholder order="2"  
        location="classpath:application.properties" ignore-unresolvable="true"/>

答案 5 :(得分:0)

感谢您的所有建议。但我发现我的问题是由目录优先级引起的。事实证明,根类路径上的属性文件的优先级高于任何属性文件,无论它们的声明顺序如何。

相关问题