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

后端 未结 2 1404
有刺的猬
有刺的猬 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: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).

提交回复
热议问题