With below XML configuration
<context:property-placeholder location="constants.properties"/>
<bean id="MyDBDetails"
class="itsmine.springcore.MyDBDetails" scope="singleton">
<property name="fName" value="${fName}" />
<property name="lName" value="${lName}" />
<property name="age" value="${age}" />
</bean>
I created a bean in my main using below 2 options: 1) using ClassPathXmlApplicationContext 2) using bean factor
The dynamic values got set when bean created using ClassPathXmlApplicationContext, but not when created using bean factory.
Could you please suggest how to make it work using bean factory ?
Thanks in advance.
When using XML declaration for bean properties, the property-placeholder is registered as a Bean Factory Post Processor
for the IoC container, thus you will have the properties values available.
However, when instantiating beans programatically through a BeanFactory
, this factory won't be aware of the properties values unless your configure a `` as its post processor:
BeanFactory factory = /* your factory initialized */;
PropertyPlaceholderConfigurer cfg = new PropertyPlaceholderConfigurer();
cfg.setLocation(new FileSystemResource("constants.properties"));
cfg.postProcessBeanFactory(factory);
Note that the org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#setLocation
accepts a org.springframework.core.io.Resource
as its argument, i.e. you can use any of the its concrete sub-implementation depending on your needs:
org.springframework.core.io.FileSystemResource
: An implementation supporting file handles.org.springframework.core.io.ClassPathResource
: An implementation for classpath resources.org.springframework.core.io.InputStreamResource
: An implementation for an InputStream
...