Spring Util:Properties Injection via Annotations into a bean

前端 未结 5 805
轻奢々
轻奢々 2020-12-23 21:19

If I have 2 .properties files setup in my Spring XML as so:



        
5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-23 21:43

    Most of time I encapsulate all properties in to a one utility and used in my apps. In that way you don't need to worry/manage each properties file in app layer. Autowired setProps(...) reads all you loaded util:properties in to the props list.

    import java.util.List;
    import java.util.Properties;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    
    @Component
    public class AppProperiesProcessor {
    
    private List props;
    private Properties mergedProperties;
    
    @Autowired
    public final void setProps(List props) {
        this.props = props;
    }
    
    public String getProp(final String keyVal) {
    
        if (null == this.mergedProperties) {
            this.mergedProperties = new Properties();
    
            for (Properties prop : this.props) {
                this.mergedProperties.putAll(prop);
            }
        }
        return mergedProperties.getProperty(keyVal);
      } 
    }
    

提交回复
热议问题