Main Tutorials

Spring Boot – How to know which connection pool is used?

In Spring Boot, @Autowired a javax.sql.DataSource, and you will know which database connection pool is using in the current running application.

1. Test Default

Spring Boot example to print a javax.sql.DataSource

Note
Read this official Spring Boot doc – Connection to a production database, to understand the algorithm for choosing a DataSource implementations – Tomcat pooling, HikariCP, Commons DBCP and Commons DBCP2.

package com.mkyong;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.sql.DataSource;

@SpringBootApplication
public class SpringBootConsoleApplication implements CommandLineRunner {

    @Autowired
    DataSource dataSource;

    public static void main(String[] args) throws Exception {
        SpringApplication.run(SpringBootConsoleApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {

        System.out.println("DATASOURCE = " + dataSource);

    }

}

Output, Spring Boot is using Tomcat pooling by default.


DATASOURCE = org.apache.tomcat.jdbc.pool.DataSource@7c541c15...

2. Test HikariCP

To switch to another connection pool, for example HikariCP, just exclude the default and include the HikariCP in the classpath.

pom.xml

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.apache.tomcat</groupId>
                    <artifactId>tomcat-jdbc</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- connection pools -->
        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
            <version>2.6.0</version>
        </dependency>

Output


DATASOURCE = HikariDataSource (HikariPool-1)
Note
Read this example – Spring Boot JDBC + MySQL + HikariCP example

References

  1. HikariCP
  2. Spring Boot JDBC + MySQL + HikariCP example

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Sasikumar Senthilnathan
6 years ago

How to get the active connections that are in use from the connection pool?

Note : Not max active connections.

Mohanchandra Mallampati
6 years ago

It is showing like this to me…….

DATASOURCE = HikariDataSource (null)

what does it mean ?

Carol
5 years ago

Thanks