Programmatic access to properties created by property-placeholder

后端 未结 9 2388
长情又很酷
长情又很酷 2020-11-29 20:21

I\'m reading properties file using context:property-placeholder. How can I access them programatically (@Value doesn\'t work - I d

相关标签:
9条回答
  • 2020-11-29 21:15

    Create beans for your properties before putting them in property-placeholder to make the properties easy to access in-code.

    Ex:

    <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        <property name="resources" value="classpath:META-INF/spring/config.properties" />
    </bean>
    
    <context:property-placeholder properties-ref="configProperties" ignore-unresolvable="true"/>
    

    Code:

    @Autowired
    private PropertiesFactoryBean configProperties;
    

    You can also use @Resource(name="configProperties")

    0 讨论(0)
  • 2020-11-29 21:16

    We use the following approach to access properties for our applications

    <util:properties id="appProperties" location="classpath:app-config.properties" />
    <context:property-placeholder properties-ref="appProperties"/>
    

    Then you have the luxury of just autowiring properties into beans using a qualifier.

    @Component
    public class PropertyAccessBean {
    
        private Properties properties;
    
        @Autowired
        @Qualifier("appProperties")
        public void setProperties(Properties properties) {
            this.properties = properties;
        }
    
        public void doSomething() {
            String property = properties.getProperty("code.version");
        }
    
    }
    

    If you have more complex properties you can still use ignore-resource-not-found and ignore-unresolvable. We use this approach to externalise some of our application settings.

     <util:properties id="appProperties" ignore-resource-not-found="true"
        location="classpath:build.properties,classpath:application.properties,
                                file:/data/override.properties"/>
     <context:property-placeholder ignore-unresolvable="true" properties-ref="appProperties"/>
    
    0 讨论(0)
  • 2020-11-29 21:17

    No you can't. PropertyPlaceholderConfigurer is a BeanFactoryPostProcessor, it is only "alive" during bean creation. When it encounters a ${property} notation, it tries to resolve that against its internal properties, but it does not make these properties available to the container.

    That said: similar questions have appeared again and again, the proposed solution is usually to subclass PropertyPlaceHolderConfigurer and make the Properties available to the context manually. Or use a PropertiesFactoryBean

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