Databases 16 min read

Alibaba Druid Connection Pool in Spring Boot: Concepts, Configuration, Monitoring and Customization

This article introduces Alibaba's Druid database connection pool, explains its core features and filters, shows how to add the Maven starter, configure properties and filters in Spring Boot, demonstrates the built‑in monitoring pages, slow‑SQL logging, Spring AOP integration, and provides methods to remove the default advertisement and retrieve monitoring data via code.

Java Architect Essentials
Java Architect Essentials
Java Architect Essentials
Alibaba Druid Connection Pool in Spring Boot: Concepts, Configuration, Monitoring and Customization

Alibaba Druid is a database connection pool designed for monitoring and extensibility, offering features such as StatFilter, WallFilter, and log4j2 integration that surpass other pools like C3P0, DBCP, and HikariCP.

1. Basic Concepts

We commonly use connection pools such as C3P0 , DBCP , Hikari , and Druid . While HikariCP is slightly faster, Druid provides powerful monitoring and extension capabilities and is an open‑source project from Alibaba.

Druid outperforms other pools (DBCP, C3P0, BoneCP, Proxool, JBoss DataSource, etc.) in functionality, performance, and scalability, and it can monitor both pool connections and SQL execution.

Spring Boot’s default datasource is HikariDataSource used with JdbcTemplate , but Druid is also a top‑choice for Java web applications.

Druid has been deployed in more than 600 Alibaba applications, proving its reliability in large‑scale production environments.

stat: Provides StatFilter for statistical monitoring.

wall: Uses WallFilter and an internal SQL parser to defend against injection attacks and support features like sharding and auditing.

log4j2: Logs SQL statements to Log4j2 for troubleshooting.

2. Related Configuration

2.1 Add Dependency

<properties>
    <java.version>1.8</java.version>
    <alibabaDruidStarter.version>1.2.11</alibabaDruidStarter.version>
</properties>

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>${alibabaDruidStarter.version}</version>
</dependency>

2.2 Configure Properties

Typical application.yml settings:

# spring configuration
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/superjson?useUnicode=true&characterEncoding=utf8&useSSL=false
    username: root
    password: 123456
    # connection pool configuration
    druid:
      initial-size: 5
      min-idle: 5
      max-active: 20
      max-wait: 60000
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 300000
      validation-query: SELECT 1 FROM user
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      filters: stat,wall,slf4j
      connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
      web-stat-filter:
        enabled: true
        url-pattern: /*
        exclusions: .js,.gif,.jpg,.png,.css,.ico,/druid/*
      stat-view-servlet:
        url-pattern: /druid/*
        allow: 127.0.0.1
        deny: 192.168.31.253
        reset-enable: false
        login-username: root
        login-password: 123456
        enabled: true

The above properties map to com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties and org.springframework.boot.autoconfigure.jdbc.DataSourceProperties .

2.3 Configure Filters

You can enable built‑in filters via the spring.datasource.druid.filters property (e.g., stat,wall,log4j ) or configure each filter individually:

# Configure StatFilter
spring.datasource.druid.filter.stat.enabled=true
spring.datasource.druid.filter.stat.db-type=h2
spring.datasource.druid.filter.stat.log-slow-sql=true
spring.datasource.druid.filter.stat.slow-sql-millis=2000

# Configure WallFilter
spring.datasource.druid.filter.wall.enabled=true
spring.datasource.druid.filter.wall.db-type=h2
spring.datasource.druid.filter.wall.config.delete-allow=false
spring.datasource.druid.filter.wall.config.drop-table-allow=false

Supported filters include StatFilter, WallFilter, ConfigFilter, EncodingConvertFilter, Slf4jLogFilter, Log4jFilter, Log4j2Filter, CommonsLogFilter, etc. Custom filters can be enabled by setting their enabled flag to true .

3. Monitoring Pages

Login page: http://localhost:8081/druid/login.html (username/password as configured).

DataSource page – shows basic datasource information and applied filters.

SQL monitoring – lists all executed SQL statements with execution time.

URL monitoring – statistics of controller request counts and durations.

Spring monitoring – AOP‑based metrics for method execution and JDBC usage.

SQL firewall – displays results of WallFilter protection.

Session monitoring – details of active sessions, creation time, last access, etc.

JSON API – provides monitoring data in JSON format.

4. SQL Monitoring

Enable WebStatFilter to collect web‑related DB statistics:

spring:
  datasource:
    druid:
      web-stat-filter:
        enabled: true
        url-pattern: /*
        exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
        session-stat-enable: true
        session-stat-max-count: 1000

5. Slow SQL Recording

Activate slow‑SQL logging via StatFilter:

spring:
  datasource:
    druid:
      filter:
        stat:
          enabled: true
          db-type: mysql
          log-slow-sql: true
          slow-sql-millis: 2000

When a query exceeds the configured threshold, it is logged.

6. Spring Monitoring

Add the AOP starter to the project:

<!-- Spring Boot AOP module -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

Configure AOP pointcuts (e.g., com.springboot.template.dao.* ) in application.yml :

spring.datasource.druid.aop-patterns="com.springboot.template.dao.*"

7. Removing Druid’s Footer Advertisement

The default Druid web UI adds an advertisement in the footer via common.js . Two ways to remove it:

7.1 Manually edit the JAR

Locate com/alibaba/druid/1.1.23/druid-1.1.23.jar!/support/http/resources/js/common.js in your local Maven repository and comment out the line // this.buildFooter(); .

7.2 Use a custom filter

Register a servlet filter that reads common.js , strips the ad HTML with regular expressions, and writes the cleaned content back:

@Configuration
@ConditionalOnWebApplication
@AutoConfigureAfter(DruidDataSourceAutoConfigure.class)
@ConditionalOnProperty(name = "spring.datasource.druid.stat-view-servlet.enabled", havingValue = "true", matchIfMissing = true)
public class RemoveDruidAdConfig {

    @Bean
    public FilterRegistrationBean removeDruidAdFilterRegistrationBean(DruidStatProperties properties) {
        DruidStatProperties.StatViewServlet config = properties.getStatViewServlet();
        String pattern = config.getUrlPattern() != null ? config.getUrlPattern() : "/druid/*";
        String commonJsPattern = pattern.replaceAll("\\*", "js/common.js");
        final String filePath = "support/http/resources/js/common.js";
        Filter filter = new Filter() {
            @Override public void init(FilterConfig filterConfig) throws ServletException {}
            @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
                chain.doFilter(request, response);
                response.resetBuffer();
                String text = Utils.readFromResource(filePath);
                text = text.replaceAll("
", "");
                text = text.replaceAll("powered.*?shrek.wang
", "");
                response.getWriter().write(text);
            }
            @Override public void destroy() {}
        };
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(filter);
        registrationBean.addUrlPatterns(commonJsPattern);
        return registrationBean;
    }
}

8. Accessing Druid Monitoring Data Programmatically

After enabling StatFilter , you can obtain datasource statistics via DruidStatManagerFacade :

@RestController
@RequestMapping("/druid")
public class DruidStatController {
    @GetMapping("/stat")
    public Object druidStat() {
        return DruidStatManagerFacade.getInstance().getDataSourceStatDataList();
    }
}

This endpoint returns a JSON list of all datasource monitoring metrics.

To the end of the article, the author encourages readers to share the content, join the architecture community, and mentions various promotional resources, but the technical core above provides a complete guide to using Druid in Spring Boot.

JavamonitoringSQLconfigurationConnection PoolSpring BootDruid
Java Architect Essentials
Written by

Java Architect Essentials

Committed to sharing quality articles and tutorials to help Java programmers progress from junior to mid-level to senior architect. We curate high-quality learning resources, interview questions, videos, and projects from across the internet to help you systematically improve your Java architecture skills. Follow and reply '1024' to get Java programming resources. Learn together, grow together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.