Configure DataSource Programmatically in Spring Boot
Last Updated :
09 Apr, 2024
In Spring Boot, DataSource configuration is the fundamental aspect and it can especially when dealing with databases. Spring Boot offers multiple ways to configure DataSource including using application.properties or application.yml files of the Spring application. There are scenarios where you might need to configure the DataSource programmatically such as when the database connection details are dynamic or need to be determined at runtime.
Key Terminologies:
- DataSource: It is an interface that can provided by the JDBC (Java Database Connectivity) API for establishing the connection with the database. It provides the methods for getting connections to the database and releasing them.
- DataSourceBuilder: It is a utility class that can provided by the Spring Boot that can help in building DataSource objects programmatically. It can allow the setting properties such as the driver class name, URL, username, and password.
- DriverClassName: It is the property used to specify the JDBC driver class name for DataSource. It is necessary to load the appropriate JDBC driver class for the database being used.
- URL: It can defined as a Uniform Resource Locator. It is a string that can specify the location of the resource. In the context of configuring the DataSource, the URL typically represents the JDBC connection URL which includes details such as the database server address, port, and the database name.
- Username and Password: These are the credentials required to authenticate and it can establish the connection with the database server. The username and password are used to the access database specified in the connection URL.
Understanding the Configuration of the DataSource Programmatically in Spring Boot
Configuring the DataSource programmatically involves creating and configuring the DataSource bean in the Spring Boot application context manually rather than relying on the external configuration files. It can allow more flexibility and control over the DataSource configuration.
Example:
public DataSource getDataSource() {
DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.driverClassName("org.postgresql.Driver");
dataSourceBuilder.url("jdbc:postgresql://localhost:5432/mydatabase");
dataSourceBuilder.username("username");
dataSourceBuilder.password("password");
return dataSourceBuilder.build();
}
In this example,
- We create the DataSourceConfig class that can be annotated with @Configuration.
- Inside the class, we can define the method annotated with the @Bean which can returns the DataSource object of the application.
- We can use the DataSourceBuilder to the create the DataSource object and set its the properties such as the driver class name, username and password.
Project to Implement the DataSource Bean Manually in the Spring Boot Application
We can demonstrate how to the configure DataSource programmatically in the Spring application.
Step 1: Create the spring project using Spring STS IDE including the below mentioned dependencies into the project.
Dependencies:
- Spring Web
- Lombok
- Spring Data JPA
- MySQL Driver
Once the the project creation completed successfully, it will look like below image,

Step 2: Create the new package named as the dataConfig, in that same package, create the java class named as the DataSourceConfig.
Go to src > org.example.springdatasourceconfig > dataConfig > DataSourceConfig and put the below code.
DataSourceConfig.java
Java
package org.example.springdatasourceconfig.dataConfig;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class DataSourceConfig {
@Bean
public DataSource getDataSource() {
DataSourceBuilder dataSourceBuilder = DataSourceBuilder.create();
dataSourceBuilder.driverClassName("com.mysql.cj.jdbc.Driver");
dataSourceBuilder.url("jdbc:mysql://localhost:3306/example?useSSL=false&serverTimezone=UTC");
dataSourceBuilder.username("root");
dataSourceBuilder.password("");
return dataSourceBuilder.build();
}
}
Step 3: Create the new package named as the controller, in that same package, create the java class named as the HomeController.
Go to src > org.example.springdatasourceconfig > controller > HomeController and put the below code:
HomeController.java:
Java
package org.example.springdatasourceconfig.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.sql.DataSource;
@RestController
public class HomeController {
private final DataSource dataSource;
@Autowired
public HomeController(DataSource dataSource) {
this.dataSource = dataSource;
}
@GetMapping("/")
public String home() {
return "Hello from Spring Boot! DataSource: " + dataSource.toString();
}
}
Step 4: Open the main class and write the following code.
Java
package org.example.springdatasourceconfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringDatasourceConfigApplication {
public static void main(String[] args) {
SpringApplication.run(SpringDatasourceConfigApplication.class, args);
}
}
pom.xml:
XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.example</groupId>
<artifactId>spring-datasource-config</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-datasource-config</name>
<description>spring-datasource-config</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Step 5: Once completed the project successfully, run the application as spring project. Refer the below output image for the better understanding.

Endpoint:
GET http://localhost:8080/
Output:

If we follow the above steps, we can demonstrate the Configuration of the DataSource programmatically in Spring Boot application.
Similar Reads
Configure Multiple Datasource in Spring Boot Application
Sometimes we build some applications that need multiple databases. Our data is arranged to store multiple databases, like one database designed for another need or another database for another need. So, in this article, we will see how to configure multiple in the Spring Boot application. Note: We a
6 min read
Spring Boot - @ConfigurationProperties
In Spring Boot, @ConfigurationProperties Annotation allows the developer to map the entire content of the properties file to a POJO (Plain Old Java Object). A property file can be either application.properties or application.yml. This annotation is useful when we have a large set of explicit configu
6 min read
Resolving Failed to Configure a DataSource Error in Spring Boot Application
In this article, we will guide you through the process of setting up the Spring Boot application with the MySQL database. We will cover how to handle the data source configuration failures and implement the automatic reconfiguration with retry mechanisms. This approach ensures that the application r
7 min read
Spring Boot - Externalized Configuration
In Spring Boot, externalized configuration is a feature that allows you to separate configuration settings from your code. This means you can change how your application behaves by modifying configuration files without needing to recompile or redeploy the application. Spring Boot supports various co
4 min read
Spring Boot Security Auto-Configuration
Spring Boot Security Auto Configuration can simplify the process of securing the Spring Boot applications by providing default security configurations. It can automate the many common security tasks such as setting up the authentication, and authorization and it can handle the common security vulner
4 min read
How to Configure Log4j 2 Logging in Spring Boot?
Log4j 2 Logging is a powerful logging framework that allows us to handle different aspects of logging in a Java application. It enables asynchronous logging and is known for its efficiency and flexibility. In Spring Boot applications, the Log4j 2 integration provides advanced logging mechanisms nece
3 min read
How to Change the Default Port in Spring Boot?
Spring Boot framework provides a default embedded server i.e. the Tomcat server for many configuration properties to run the Spring Boot application. The application runs on the default port which is 8080. As per the application need, we can also change this default port for the embedded server. In
4 min read
Spring Boot - Cloud Configuration Server
In microservices, we have several different services responsible for different functionalities. These services act like smaller application modules, which together form the application. Each of these modules has its own responsibility, based on the business logic of the application being built. Thes
10 min read
Spring Boot - Create a Custom Auto-Configuration
Usually, we might be taking a maven project or grade project for Spring Boot related projects. We will be adding the dependencies in pom.xml (in case of a maven project). In a spring application, Spring Boot auto-configuration helps to automatically configure by checking with the jar dependencies th
4 min read
Spring Boot - Auto-configuration
Spring Boot is heavily attracting developers toward it because of three main features as follows: Auto-configuration - such as checking for the dependencies, the presence of certain classes in the classpath, the existence of a bean, or the activation of some property.An opinionated approach to confi
5 min read