Spring Environment Property Source Configuration

后端 未结 5 1717
感动是毒
感动是毒 2020-12-28 08:33

I\'m working on an application library with a utility class called \"Config\" which is backed by the Spring Environment object and provides strongl

5条回答
  •  隐瞒了意图╮
    2020-12-28 09:20

    I came up with the following which seems to work, but I'm fairly new to Spring, so I'm not so sure how it will hold up under different use cases.

    Basically, the approach is to extend PropertySourcesPlaceholderConfigurer and add a setter to allow the user to easily configure a List of PropertySource objects in XML. After creation, the property sources are copied to the current Environment.

    This basically allows the property sources to be configured in one place, but used by both placholder configuration and Environment.getProperty scenarios.

    Extended PropertySourcesPlaceholderConfigurer

    public class ConfigSourcesConfigurer 
            extends PropertySourcesPlaceholderConfigurer
            implements EnvironmentAware, InitializingBean {
    
        private Environment environment;
        private List sourceList;
    
        // Allow setting property sources as a List for easier XML configuration
        public void setPropertySources(List propertySources) {
    
            this.sourceList = propertySources;
            MutablePropertySources sources = new MutablePropertySources();
            copyListToPropertySources(this.sourceList, sources);        
            super.setPropertySources(sources);
        }
    
        @Override
        public void setEnvironment(Environment environment) {
            // save off Environment for later use
            this.environment = environment;
            super.setEnvironment(environment);
        }
    
        @Override
        public void afterPropertiesSet() throws Exception {
    
            // Copy property sources to Environment
            MutablePropertySources envPropSources = ((ConfigurableEnvironment)environment).getPropertySources();
            copyListToPropertySources(this.sourceList, envPropSources);
        }
    
        private void copyListToPropertySources(List list, MutablePropertySources sources) {
    
            // iterate in reverse order to insure ordering in property sources object
            for(int i = list.size() - 1; i >= 0; i--) {
                sources.addFirst(list.get(i));
            }
        }
    }
    

    beans.xml file showing basic configuration

    
        
        
    
        
            
                
                    
                    
                        
                    
                
            
        
        
            
        
    
    

提交回复
热议问题