Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

spring boot : How to set spring properties dynamically

There are so many properties which can be defined in application.properties of spring boot application.

But I want to pass properties to configure ssl to spring from inside the code.

server.ssl.enabled=true
# The format used for the keystore 
server.ssl.key-store-type=PKCS12
# The path to the keystore containing the certificate
server.ssl.key-store=keys/keystore.jks
# The password used to generate the certificate
server.ssl.key-store-password=changeit
# The alias mapped to the certificate
server.ssl.key-alias=tomcat

So as these will be spring defined properties to be used from application.properties. I just want to set them from the code based on some logic.

For non spring application, I still have some idea that they can be passed as application, session or context properties but I am not aware on how this works in spring.

Any help would be appreciated.

like image 571
Onki Avatar asked Dec 04 '22 18:12

Onki


2 Answers

Since you know the properties to enable SSL in the spring boot app. You can pass these properties programmatically in your spring boot application like this:

@SpringBootApplication
public class SpringBootTestApplication {
    public static void main(String[] args) {

//      SpringApplication.run(SpringBootTestApplication.class, args);

        Properties props = new Properties();
        props.put("server.ssl.key-store", "/home/ajit-soman/Desktop/test/keystore.p12");
        props.put("server.ssl.key-store-password", "123456");
        props.put("server.ssl.key-store-type", "PKCS12");
        props.put("server.ssl.key-alias", "tomcat");

        new SpringApplicationBuilder(SpringBootTestApplication.class)
            .properties(props).run(args);
    }
}

As you can see I have commented out this: SpringApplication.run(SpringBootTestApplication.class, args); and used SpringApplicationBuilder class to add properties to the app.

Now, these properties are defined in the program, You can apply condition and change property values based on your requirements.

like image 72
Ajit Soman Avatar answered Dec 20 '22 05:12

Ajit Soman


In Spring Boot, you can read and edit propeties using System.getProperty(String key) and System.setProperty(String key, String value)

public static void main(String[] args) {

    // set properties
    System.setProperty("server.ssl.enabled", "true");
    System.setProperty("server.ssl.key-store-type", "PKCS12");
    System.setProperty("server.ssl.key-store", "keys/keystore.jks");
    System.setProperty("server.ssl.key-store-password", "changeit");
    System.setProperty("server.ssl.key-alias", "tomcat");

    // run
    SpringApplication.run(DemoApplication.class, args);
}

Note:

This will overwrite the static properties (not all but the overwritten ones).

like image 21
Tien Do Nam Avatar answered Dec 20 '22 07:12

Tien Do Nam