Hi I'm using spring boot. I would like to dynamically replace the contents of a variable in the properties file.
This is my file: message.properties
message=Welcome ${bean.name} to my website
I would like to know if there is any way to change the value of my variable. Thanks
To change properties in a file during runtime, we should place that file somewhere outside the jar. Then we tell Spring where it is with the command-line parameter –spring. config. location=file://{path to file}.
Another method to access values defined in Spring Boot is by autowiring the Environment object and calling the getProperty() method to access the value of a property file.
Spring boot provides command line configuration called spring.config.name using that we can change the name of application. properties. Here properties file name will be my-config.
If it comes to messages.properties
file, you don't have to change dynamically its content. Instead you can use message variables. Take a look at this example:
messages.properties:
message=Welcome {0} to my website
If you process that message using MessageSource
bean, you can get this message with:
messageSource.getMessage("message", new Object[] { "Test" }, LocaleContextHolder.getLocale())
The returned string in that case is:
Welcome Test to my website
Of course you need to inject MessageSource
to the class (controller,service) before you can use this exemplary code:
@Autowired
MessageSource messageSource
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