How do I configure Spring to partially and optionally override properties?

后端 未结 2 1368
有刺的猬
有刺的猬 2021-02-11 04:25

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:

  • db
相关标签:
2条回答
  • 2021-02-11 04:52

    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");
            }
        }
    
    0 讨论(0)
  • 2021-02-11 04:56

    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).

    0 讨论(0)
提交回复
热议问题