问题
I would like to maintain a list of application properties like service endpoints, application variables, etc. in a Spring application. These properties should be able to updated dynamically (possibly through an web page by system administrator).
Does spring has an inbuilt feature to accomplish this requirement?
回答1:
I am not sure spring has an implementation for updating the properties file dynamically.
You can do something like reading the properties file using FileInputStream into a Properties object. Then you will be able to update the properties. Later you can write back the properties to the same file using the FileOutputStream.
// reading the existing properties
FileInputStream in = new FileInputStream("propertiesFile");
Properties props = new Properties();
props.load(in);
in.close();
// writing back the properties after updation
FileOutputStream out = new FileOutputStream("propertiesFile");
props.setProperty("property", "value");
props.store(out, null);
out.close();
回答2:
Externalizing properties, take a look here
Spring loads these properties which can be configured at runtime and accessed in your application in different ways.
回答3:
Add your own implementation of a PropertySource to your Environment.
Warning: Properties used by @ConfigurationProperties and @Value annotations are only read once on application startup, so changing the actual property values at runtime will have no effect (until restarted).
回答4:
I am not sure, but check if you can make use @ConfigurationProperties of Spring boot framework.
@ConfigurationProperties(locations = "classpath:application.properties", ignoreUnknownFields = false, prefix = "spring.datasource")
- You can keep this application.properties file in you classpath
- Change the properties in this file without redeploying the application
Java Experts - I am just trying to explore my view. Corrections are always welcome.
Edit - I read a good examples on @PropertySource here
来源:https://stackoverflow.com/questions/41192085/how-to-maintain-update-application-properties-dynamically-in-spring