I'm using properties file with Spring 3. When Spring initializes its contex it loads the properties file and puts it in all beans with @Value annotation.
I want to have a possibility to update some properties in a file, and expose a JMX on the server that will reload the new properties to Spring - without restarting the server, and reloading its context.
Can I implement this by using some Spring method to reload properties and populate them to all beans, or should I write something like this by my own?
Reloading Properties by Actuator and Cloud Thus, we need Spring Cloud to add a /refresh endpoint to it. This endpoint reloads all property sources of Environment, and then publishes an EnvironmentChangeEvent. Spring Cloud has also introduced @RefreshScope, and we can use it for configuration classes or beans.
include=refresh: this is actuator property which will help us to refresh the properties without restarting the server.
spring. config. location ( SPRING_CONFIG_LOCATION ) is the file to load (e.g. a classpath resource or a URL). A separate Environment property source is set up for this document and it can be overridden by system properties, environment variables or the command line.
Environment-Specific Properties File. If we need to target different environments, there's a built-in mechanism for that in Boot. We can simply define an application-environment.properties file in the src/main/resources directory, and then set a Spring profile with the same environment name.
I would suggest replacing the java.util.Properties
with a PropertiesConfiguration
from the Apache Commons Configuration project. It supports automatic reloading, either by detecting when the file changes, or by triggering through JMX.
I think there is no common way of doing that. The most "clean" one would be to shut down the Spring context and build it from scratch. For example, consider using of DBCP connection pool and updating it's database connection URL. This means that the pool has to be properly shut down, then new object has to be created and then all references to the pool has to be updated as well. Now, some beans may take connection from that pool, and updating the pool config means that you need to re-request connections somehow. Thus, beans may need to know how to do that, which is not common.
I'd suggest to create separate bean with configuration and update events, and put that bean as dependency for all beans you need to know about configuration changes. Then you may use Apache Commons Configuration for waching file changes and propagate configuration updates.
Perhaps use JMS is good (if you later going distribute your app).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With