更新Spring注入的属性文件以包含上次运行时间戳

我有一个应用程序,它使用Spring加载的属性文件。 然后将Properties实例注入几个类。 问题是这些属性中的一些已更新 – 例如我们有一个lastRun时间戳,我们想要存储在这里。 也许有更好的方法来存储这样的东西(建议欢迎),但我怎样才能更新属性文件?

 

props.store(...)方法需要写入或输出流(我假设所有这些都是未知的,因为Spring处理此加载)。

有没有更好的方法或者我应该从Spring context.xml传递文件路径并将其发送到各种bean并以旧式方式加载/存储属性文件?

PropertiesFactoryBean没有location属性的访问者,但您可以从BeanDefinition获取location属性。

 BeanDefinition def = ctx.getBeanFactory().getBeanDefinition("props"); String location = def.getPropertyValues().getPropertyValue("location").getValue(); File file = ctx.getResource(location).getFile(); 

编辑

包括一个样本类来完成它。 您可以在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; } }