Having spring bean properties refreshed automatica

2019-02-03 18:57发布

问题:

I'm using Spring 2.5.6. I have a bean whose properties are being assign from a property file via a PropertyPlaceholderConfigurer. I'm wondering whether its possible to have the property of the bean updated when the property file is modified. There would be for example some periodic process which checks the last modified date of the property file, and if it has changed, reload the bean.

I'm wondering if there is already something that satisfies my requirements. If not, what would be the best approach to solving this problem?

Thanks for your help.

回答1:

Might also look into useing Spring's PropertyOverrideConfigurer. Could re-read the properties and re-apply it in some polling/schedular bean.

It does depend on how the actual configured beans use these properties. They might, for example, indirectly cache them somewhere themself.



回答2:

If you want dynamic properties at runtime, perhaps another way to do it is JMX.



回答3:

One way to do this is to embed a groovy console in your application. Here's some instructions. They were very simple to do, btw - took me very little time even though I'm not that familiar with groovy.

Once you do that you can simply go into the console and change values inside the live application on the fly.



回答4:

You might try to use a custom scope for the bean that recreates beans on changes of the properties file. See my more extensive answer here.



回答5:

Spring Cloud Config has facilities to change configuration properties at runtime via the Spring Cloud Bus and using a Cloud Config Server. The configuration or .properties or .yml files are "externalized" from the Spring app and instead retrieved from a Spring Cloud Config Server that the app connects to on startup. That Cloud Config Server retrieves the appropriate configuration .properties or .yml files from a GIT repo (there are other storage solutions, but GIT is the most common). You can then change configuration at runtime by changing the contents of the GIT repo's configuration files--The Cloud Config Server broadcasts the changes to any Client Spring applications via the Spring Cloud Bus, and those applications' configuration is updated without needing a restart of the app. You can find a working simple example here: https://github.com/ldojo/spring-cloud-config-examples