Categories
Java

Dynamic database connection properties for Spring Boot

How to set Spring Boot database connection properties dynamically, in the application main. Also we explain the priority order between static and dynamic properties.

1) The usual static way

Usually, Spring Boot properties are set in the application properties file, which has following path:

src/main/resources/application.properties

and following content:

spring.datasource.url = jdbcUrl
spring.datasource.username = dbUsername
spring.datasource.password = dbPassword

2) The dynamic programmatic way

It is possible to setup the database connection properties dynamically, during the Spring Boot app startup. To achieve this, use the function:

SpringApplication.setDefaultProperties()

in your application’s main:

package com;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import java.util.*;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(Application.class);

        String jdbcUrl = "your-jdbcUrl";
        String dbUsername = "your-dbUsername";
        String dbPassword = "your-dbPassword";

        Map<String, Object> props = new HashMap<>();
        props.put("spring.datasource.url",jdbcUrl);
        props.put("spring.datasource.username", dbUsername);
        props.put("spring.datasource.password", dbPassword);
        app.setDefaultProperties(props);

        app.run(args);
    }
}

3) Priority order between static and dynamic properties

The Spring Boot application will automatically look for the file:

src/main/resources/application.properties

If a property is setup there, then it will have priority over the same property that is also set dynamically in the code via:

SpringApplication.setDefaultProperties()

So if a property is already setup in application.properties and you want to override it dynamically in the code, then be sure to first remove the property fromapplication.properties.

Leave a Reply

Your email address will not be published.