无法覆盖spring boot中的属性

时间:2014-11-13 18:41:24

标签: java spring spring-mvc

是否有在子上下文中覆盖父上下文的spring boot属性?

我尝试过各种选择:

1)父母和母亲相应XML中的子项:与非引导项目类似的属性占位符排序(子顺序>父顺序):不起作用

<context:property-placeholder location="classpath:parent-config.properties" order="-10"
        ignore-unresolvable="true" ignore-resource-not-found="true" />
<context:property-placeholder location="classpath:child-config.properties" order="-5"
        ignore-unresolvable="true" ignore-resource-not-found="true" />

2)父母和父母都在相应Java中的子项@Configuration:不工作

@PropertySource(value={"classpath:parent-config.properties"}, ignoreResourceNotFound=true)
@PropertySource(value={"classpath:child-config.properties"})

3)XML property-placeholder&amp ;; Java中的孩子@Configuration工作一段时间,而不是总是

<context:property-placeholder location="classpath:parent-config.properties" order="-10"
            ignore-unresolvable="true" ignore-resource-not-found="true" />
 @PropertySource(value={"classpath:child-config.properties"})

4)父母和母亲@PropertySource @Configuration的{​​child}中的孩子:工作

@PropertySource(value={"classpath:parent-config.properties", "classpath:child-config.properties"})

当我导入/扩展已经具有&#34; classpath:parent-config.properties&#34;的父上下文时,我不应该再次提到子配置中的父配置。 有没有适当的解决方案??

2 个答案:

答案 0 :(得分:0)

Spring Boot会自动从classpath(src / main / resources,如果您使用的是Maven)加载application.properties。

请看Externalized Configuration chapter of Spring Boot documentation

答案 1 :(得分:0)

如果parent-config.properties和child-config.properties中都存在相同的属性,那么最后的@PropertySource注释将“获胜”并覆盖该值。请参阅此处的最后一部分:http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/PropertySource.html

在这种情况下,#4有效,因为您在同一个注释中指定了两个属性文件,并且稍后正在处理child-config.properties。

其他人可能工作或不工作,具体取决于检测到这些属性文件的顺序。由于@PropertySource注释是自动扫描的,因此很难控制订单。

您的选择是:

  1. 确保属性仅存在于父或子config.properties
  2. 使用程序化PropertySource API(MutablePropertySources addFirst / addLast方法)
  3. 这是我找到的示例示例 - http://scottfrederick.cfapps.io/blog/2012/05/30/Custom-PropertySource-in-Spring-3.1---Part-3

    还有MutablePropertySources的文档 - http://cloud-vm45.cloud.cnaf.infn.it:8085/webdav/noauth/spring-framework-3.2.8.RELEASE/docs/javadoc-api/org/springframework/core/env/MutablePropertySources.html

相关问题