Open In App

Configure DataSource Programmatically in Spring Boot

Last Updated : 09 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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,

File Structure


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.

Application Started

Endpoint:

GET http://localhost:8080/

Output:

Output in Browser

If we follow the above steps, we can demonstrate the Configuration of the DataSource programmatically in Spring Boot application.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads