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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With