I would like to have a properties setup which can, on certain environments, override specific properties. For example, our default JDBC properties for dev are:
I had a similar issue with overwriting already existing properties in integration tests
I came up with this solution:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {
SomeProdConfig.class,
MyWebTest.TestConfig.class
})
@WebIntegrationTest
public class MyWebTest {
@Configuration
public static class TestConfig {
@Inject
private Environment env;
@PostConstruct
public void overwriteProperties() throws Exception {
final Map<String,Object> systemProperties = ((ConfigurableEnvironment) env)
.getSystemProperties();
systemProperties.put("some.prop", "test.value");
}
}
Your configuration is flawed when configuring BeanFactoryPostProcessor
with java config the methods should be static. However it can be even easier, instead of registering your own PropertySourcesPlaceholderConfigurer
utilize the default @PropertySource
support.
Rewerite your jav config to the following
@Configuration
@PropertySource(name="main", value= "${spring.profiles.active}.main.properties")
public class PropertyTestConfiguration {
@Autowired
private Environment env;
@PostConstruct
public void initialize() {
String resource = env.getProperty("spring.profiles.sub") +".main.properties";
Resource props = new ClassPathResource(resource);
if (env instanceof ConfigurableEnvironment && props.exists()) {
MutablePropertySources sources = ((ConfigurableEnvironment) env).getPropertySources();
sources.addBefore("main", new ResourcePropertySource(props));
}
}
@Bean
public Main_PropertyTest main_PropertyTest(@Value("${main.property}") String property) {
Main_PropertyTest main_PropertyTest = new Main_PropertyTest(property);
return main_PropertyTest;
}
}
This should first load the dev.main.properties
and additionally the test.main.properties
which will override the earlier loaded properties (when filled ofcourse).