简体   繁体   中英

I want to write a property to application.properties before spring boot application start

I want to write a property to application.properties before spring boot application start.

        Properties properties = new Properties();

        try {
            properties.load(new FileInputStream("src/main/resources/application.properties"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        if (properties.getProperty("name") == null) {
            OutputStream os = null;
            Properties prop = new Properties();
            prop.setProperty("name", "WriteTheName");
            try {
                os = new FileOutputStream("src/main/resources/application.properties", true);
                prop.store(os, "Dynamic Property File");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        else
        {
            System.out.println("Already available Name %%%%%%%%%%%%%%%%%%%%%%%");
        }

The above code, i used with CommandLineRunner's run method. This is writing the value after application started. Please let me know if there is a way to write the property value before application start up.

When the app is built and started, you won't have access to src/main/resources .

Writing a properties file after starting an app but before starting to load the Spring context is not a good approach. One of the few use cases I see with this is during an application installation where maybe some random ids would have to be generated but this is the job of the installer and not the job of the application.

Alternatively you can pass property values to a Spring Boot application as:

Assuming the property you would like to use is named: my.property.key :

java -Dmy.property.key=value -jar application.jar
java -jar application.jar --my.property.key=value
MY_PROPERTY_KEY=value java -jar application.jar

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM