Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatic access to properties created by property-placeholder

I'm reading properties file using context:property-placeholder. How can I access them programatically (@Value doesn't work - I don't know property titles at the moment of developing)?

The main problem is I can't change applicationContext.xml file because it's setted up by "parent" framework

ps. It's strange but Environment.getProperty returns null

like image 988
fedor.belov Avatar asked Jul 10 '12 14:07

fedor.belov


2 Answers

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

like image 175
Sean Patrick Floyd Avatar answered Nov 12 '22 04:11

Sean Patrick Floyd


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"/> 
like image 20
mattyboy Avatar answered Nov 12 '22 03:11

mattyboy