问题
I have an application which makes used of a properties file loaded by Spring. The Properties instance is then injected into a few classes. The question is some of these properties are updated - for example we have a lastRun timestamp which we want to store here. Maybe there is a better way to go about storing something like this (suggestions welcome), but how can I go about updating the properties file?
<util:properties id="props" location="some.properties"/>
The props.store(...)
method requires either a write or an output stream (all of which I'm assuming is unknown as Spring handles this loading)..?
Is there a better approach or should I just be passing in the file path from the Spring context.xml and sending it to various beans and loading/storing the properties file the old fashioned way?
回答1:
The PropertiesFactoryBean don't have accessor for location property but you can get the location property from BeanDefinition.
BeanDefinition def = ctx.getBeanFactory().getBeanDefinition("props");
String location = def.getPropertyValues().getPropertyValue("location").getValue();
File file = ctx.getResource(location).getFile();
EDIT
Include a sample class to do it. You can define the bean in bean the definition file and inject where appropiate.
/**
* 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;
}
}
来源:https://stackoverflow.com/questions/9322436/updating-a-properties-file-injected-by-spring-to-include-a-last-run-timestamp