I am trying to update the value of a key in application.properties before application runs
This is the snippet I'm using
import java.io.*;
import java.util.Properties;
import java.util.Scanner;
public class ModifyPropertiesFileDynamically {
public static void main(String[] args) {
modifyPropertiesFile();
SpringApplication.run(YourApplication.class, args);
}
private static void modifyPropertiesFile() {
Properties properties = new Properties();
try (InputStream inputStream = new FileInputStream("src/main/resources/application.properties")) {
properties.load(inputStream);
properties.setProperty("custom.property", "qwerty");
try (OutputStream outputStream = new FileOutputStream("src/main/resources/application.properties")) {
properties.store(outputStream, null);
System.out.println(properties.getProperty("custom.property"));
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
This updates the value in application.property with new value but after app runs for the first run only it's still taking the older value.
Can someone help with why this is happening and what to do to avoid this so the value gets updated in 1st run itself?
Instead of directly updating the application.properties file, consider a more robust approach. For dynamic properties, I recommend to use environment variables.
This not only provides a more flexible and scalable solution but also allows for the dynamic management of variables in your application.
For exmaple: