Spring property file loader: how to update properties at runtime when they are updated in a file?

I am using PropertyPlaceholderConfigurer to load properties file using spring.

<bean id="placeholderProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
       <property name="locations">
          <list>        
             <value>file:${applicationProperties}</value>    
          </list>
       </property>
    </bean>

      

I am overriding this PropertyPlaceholderConfigurer to store the entire key value pair in the map. Now when this properties file is updated and saved to the file system, this map should be updated with the new values ​​at runtime.

How can this requirement be achieved?

+3


source to share


1 answer


You need to use beanfactory postprocessor:

Application-context.xml

<bean id="connection" class="com.bfpp.beans.Connectionmanager">
<property name="url" value="${db.url}"></property>
<property name="username" value="${db.un}"></property>
<property name="pass" value="${db.pwd}"></property>
</bean>

<bean id="pphc" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:db.properties"></property>
</bean>
</beans>

      

write the appropriate connection bean In test class



        ApplicationContext ctx=new ClassPathXmlApplicationContext("com/bfpp/common/application-context.xml");
        /*BeanFactory factory=new XmlBeanFactory(new ClassPathResource("com/bfpp/common/application-context.xml"));*/
        /*BeanFactoryPostProcessor bfpp=factory.getBean("pphc",BeanFactoryPostProcessor.class);
        bfpp.postProcessBeanFactory((ConfigurableListableBeanFactory) factory);*/
        Connectionmanager c=ctx.getBean("connection",Connectionmanager.class);
        System.out.println(c);

      

write db.properties

db.url=jdbc:odbc:thin@1521:xe
db.un=username
db.pwd=password

      

They will be replaced in the XML file before the bean is initialized. In the case, the beanfactory

beans will be loaded when we call the method getBean()

, so the code in the comments is not required if we are using the applicationcontext as it creates the beans at creation time itself ClassPathXmlApplicationContext

.

-2


source







All Articles