spring - @Import 覆盖 Spring @PropertySource

标签 spring properties

我有一处特性 test=default在 DefaultConfig 类中,我使用 @PropertySource 注释使它们可用。

@Configuration
@PropertySource("classpath:default.properties")
public class DefaultConfig {}

然后我希望能够覆盖到 test=override ,它位于类 OverrideConfig 的不同属性文件中,所以我再次使用 @PropertySource。

@Configuration
@Import(DefaultConfig.class)
@PropertySource("classpath:override.properties")
public class OverrideConfig {}

我配置了一个测试来证明它有效。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={OverrideConfig.class})
public class TestPropertyOverride {

    @Autowired
    private Environment env;

    @Test
    public void propertyIsOverridden() {
        assertEquals("override", env.getProperty("test"));
    }

}

当然不是。

org.junit.ComparisonFailure: expected:<[override]> but was:<[default]>

最大化调试,我可以看到发生了什么:

StandardEnvironment:107 - Adding [class path resource [default.properties]] PropertySource with lowest search precedence
StandardEnvironment:107 - Adding [class path resource [override.properties]] PropertySource with lowest search precedence

似乎倒退了。我是否犯了一个简单的错误或误解了这一点,或者您是否希望@Import-ed 配置类中的@PropertySource 定义的属性被@Import-ing 类中的@PropertySource 中定义的属性覆盖?

最佳答案

这是 Helder Sousa 的解决方案,写为 a comment of the JIRA issue由 OP 创建:

[T]he behaviour available in spring xml (one xml importing another xml) is achievable using nested configurations:

@Configuration
@PropertySource("classpath:default.properties")
public class DefaultConfig {}
@Configuration
@PropertySource("classpath:override.properties")
public class OverrideConfig {

    @Configuration
    @Import(DefaultConfig.class)
    static class InnerConfiguration {}

}

With this setup, the properties will be gather in the proper order.

关于spring - @Import 覆盖 Spring @PropertySource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15577125/

相关文章:

javascript - JS中是否可以重载对对象属性的访问

spring - HTTP 状态 404 – 基本 Spring Boot 程序未找到

java - 是否有真实世界的 Spring 和 Hibernate 示例的来源?

java - 从 IDE 运行 Spring Web 与从 jar 文件运行 Spring Web

mysql - jpa/spring/hibernate中的简单乐观锁问题

css - 为什么我们在normalize.css中加入这行代码?

java - 切换正在运行的 Java 程序的语言的最佳做法是什么

file - 在grails中创建Property文件并在main.gsp布局中显示内容

c# - xsd.exe 自动实现的属性

mysql - HikariCP Spring + Hibernate + MySQL : Method not found: setMaxLifetime