【问题标题】:Spring property file loader: how to update properties at runtime, whenever they are updated in file?Spring属性文件加载器:如何在运行时更新属性,无论何时在文件中更新它们?
【发布时间】:2015-02-26 06:59:45
【问题描述】:
我正在使用 PropertyPlaceholderConfigurer 使用 spring 加载属性文件。
<bean id="placeholderProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>file:${applicationProperties}</value>
</list>
</property>
</bean>
我已覆盖此 PropertyPlaceholderConfigurer 以将所有键值对存储在 Map 中。现在的要求是,每当此属性文件更新并保存在文件系统上时,此映射应在运行时使用新值更新。
如何实现这个要求?
【问题讨论】:
标签:
java
spring
jakarta-ee
properties
【解决方案1】:
你必须使用 beanfactory 后处理器:
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>
编写各自的连接bean
在测试课中
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);
编写 db.properties
db.url=jdbc:odbc:thin@1521:xe
db.un=username
db.pwd=password
这些将在 bean 初始化发生之前在 xml 文件中被替换。
在beanfactory 的情况下,当我们调用getBean() 方法时将加载bean,因此如果我们使用applicationcontext,则不需要cmets 中的代码,因为它会在创建ClassPathXmlApplicationContext 本身时创建bean。