I have a spring-boot
application. Under the run folder, there is an additional config file:
dir/config/application.properties
When the applications starts, it uses the values from the file and injects them into:
@Value("${my.property}")
private String prop;
Question: how can I trigger a reload of those @Value
properties?
I want to be able to change the application.properties
configuration during runtime, and have the @Value
fields updated (maybe trigger that update by calling a /reload
servlet inside the app).
But how?
For Reloading properties, spring cloud has introduced @RefreshScope annotation which can be used for refreshing beans. Spring Actuator provides different endpoints for health, metrics. but spring cloud will add extra end point /refresh to reload all the properties.
To add different files you can use the spring. config. location properties which takes a comma separated list of property files or file location (directories). The one above will add a directory which will be consulted for application.
You can do something like reading the properties file using FileInputStream into a Properties object. Then you will be able to update the properties.
Use the below bean to reload config.properties every 1 second.
@Component
public class PropertyLoader {
@Autowired
private StandardEnvironment environment;
@Scheduled(fixedRate=1000)
public void reload() throws IOException {
MutablePropertySources propertySources = environment.getPropertySources();
PropertySource<?> resourcePropertySource = propertySources.get("class path resource [config.properties]");
Properties properties = new Properties();
InputStream inputStream = getClass().getResourceAsStream("/config.properties");
properties.load(inputStream);
inputStream.close();
propertySources.replace("class path resource [config.properties]", new PropertiesPropertySource("class path resource [config.properties]", properties));
}
}
Your main config will look something like :
@EnableScheduling
@PropertySource("classpath:/config.properties")
public class HelloWorldConfig {
}
The instead of using @Value, each time you wanted the latest property you would use
environment.get("my.property");
Note
Although the config.properties in the example is taken from the classpath, it can still be an external file which has been added to the classpath.
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