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:


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:


in your application’s main:

package com;

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

import java.util.*;

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.username", dbUsername);
        props.put("spring.datasource.password", dbPassword);

3) Priority order between static and dynamic properties

The Spring Boot application will automatically look for the file:


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


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

Leave a Reply

Your email address will not be published. Required fields are marked *