Updating a properties file injected by Spring to include a last run timestamp

徘徊边缘 提交于 2020-01-01 07:05:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!