Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding Spring @PropertySource by @Import

I have a property test=default in class DefaultConfig, and I'm making them available using @PropertySource annotation.

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

I then want to be able to override to test=override, which is in a different properties file in class OverrideConfig, so I again use @PropertySource.

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

I configure a test to prove that it works.

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

    @Autowired
    private Environment env;

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

}

Except of course it does not.

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

Maxing out debug, I can see what's happening:

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

It seems backwards. Am I making a simple mistake or misthinking this, or would you expect the properties defined by an @PropertySource in an @Import-ed configuration class to be overridden by properties defined in am @PropertySource in the @Import-ing class?

like image 806
brabster Avatar asked Mar 22 '13 18:03

brabster


1 Answers

Here is a solution by Helder Sousa, written as a comment of the JIRA issue created by the 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.

like image 169
kuporific Avatar answered Sep 20 '22 05:09

kuporific