我有一个应用程序,它使用 Spring 加载的属性文件。然后将 Properties 实例注入到几个类中。问题是其中一些属性已更新 - 例如我们有一个要存储在这里的lastRun时间戳。也许有更好的方法来存储这样的东西(欢迎建议),但是我该如何更新属性文件呢?
<util:properties id="props" location="some.properties"/>
The props.store(...)
方法需要写入或输出流(我假设所有这些都是未知的,因为 Spring 处理此加载)..?
是否有更好的方法,或者我应该只是从 Spring context.xml 传递文件路径并将其发送到各种 bean 并以老式方式加载/存储属性文件?
PropertiesFactoryBean 没有位置属性的访问器,但您可以从 BeanDefinition 获取位置属性。
BeanDefinition def = ctx.getBeanFactory().getBeanDefinition("props");
String location = def.getPropertyValues().getPropertyValue("location").getValue();
File file = ctx.getResource(location).getFile();
EDIT
包括一个示例类来执行此操作。您可以在 bean 定义文件中定义 bean 并在适当的位置注入。
/**
* Update Spring managed properties
*/
public class SpringPropertyUpdater implements ApplicationContextAware {
private ConfigurableApplicationContext ctx;
private static final String LOCATION_PROPERTY = "location";
private static final Log log = LogFactory.getLog(SpringPropertyUpdater.class);
/**
* Update managed properties with new value
*/
public void updateProperties(String name, Properties props, String comments) {
ConfigurableListableBeanFactory fb = ctx.getBeanFactory();
BeanDefinition bf = fb.getBeanDefinition(name);
String location = (String) bf.getPropertyValues().getPropertyValue(LOCATION_PROPERTY).getValue();
Resource res = ctx.getResource(location);
try {
File file = res.getFile();
props.store(new FileOutputStream(file), comments);
} catch (IOException e) {
log.error(e);
}
}
/**
* {@inheritDoc}
*/
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.ctx = (ConfigurableApplicationContext) applicationContext;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)