Updating values in application.properties before application runs

46 Views Asked by At

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?

2

There are 2 best solutions below

0
Kendy Alvarado On

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:

username = ${userName}
password = ${password}
0
Kathrin Geilmann On

You write your modified property file into the source folder after building your program. So, the .jar created by your build process contains the original file.

Even if you just start from your IDE, the IDE will not pass the source folders as classpath to the application, but the target (or out, build, whatever the IDE calls it) folder.

Depending on why you want to modify the application.properties, there might be a bunch of other possibilities with application.properties outside of the jar, using profiles, using environement variables and more. Direct modification of the application properties should never be needed,

The easiest variant to add an additional property like in your example is to use the command line, i.e. just start your programm with --custom.property=qwerty as parameter.

If you really need to manipulate the environement before app start use an EnvironmentPostProcessor instead of file manipulation.