Reputation: 49
I have a requirement where I get the DB URI, DB URL etc at runtime in JavaCode. This value needs to be available to application.properties for it to make a DB call.
I always used Spring boot to retrieve values assigned in application.properties file but not the other way How do I achieve something similar db.uri = {comingFromJavaCode}
Upvotes: 3
Views: 4457
Reputation: 131
In Spring Boot, you can add or update a property in the application.properties programmatically by using System.setProperty(String key, String value)
@SpringBootApplication
public class SpringBootTestApplication {
public static void main(String[] args) {
System.setProperty("key", "value");
SpringApplication.run(SpringBootTestApplication.class, args);
}
}
Note: Values defined using System.setProperty(String key, String value) takes precedence over the values in the application.properties files
Upvotes: 0
Reputation: 7361
Your question has already been answered in this stackoverflow thread. Write/Update properties file value in spring
By the way, the application.properties file is only read by the spring boot application once during startup. Adding any new values to the file at runtime has no effect. The following stackoverflow thread explains how to reload the application.properties
file during loadtime. How can I reload properties file in Spring 4 using annotations? . This article can also be of use: https://docs.spring.io/spring/docs/3.2.6.RELEASE/javadoc-api/org/springframework/context/support/ReloadableResourceBundleMessageSource.html
Upvotes: 2