Backend Development 17 min read

Master Druid: Configure, Monitor, and Optimize Java Connection Pools in Spring Boot

This guide explains Druid's core concepts, how to add Maven dependencies, configure properties, enable monitoring filters, customize the admin servlet, remove built‑in ads, and retrieve runtime statistics, providing a complete tutorial for integrating Druid with Spring Boot applications.

Su San Talks Tech
Su San Talks Tech
Su San Talks Tech
Master Druid: Configure, Monitor, and Optimize Java Connection Pools in Spring Boot

1. Basic Concepts

Druid is considered the best Java database connection pool, offering powerful monitoring and extensibility compared to HikariCP, which is slightly faster but lacks Druid's features. Developed by Alibaba, Druid surpasses other pools such as DBCP, C3P0, BoneCP, Proxool, and JBoss DataSource.

stat

: Built‑in StatFilter for statistical monitoring.

wall

: WallFilter protects against SQL injection by parsing SQL.

log4j2

: Logs SQL statements via Log4j2 for troubleshooting.

2. Adding Dependencies

<!-- Alibaba Druid starter -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.23</version>
</dependency>

<!-- MySQL 8 driver -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

<!-- Log4j2 for logging -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

<!-- Exclude default HikariCP from MyBatis starter -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
    <exclusions>
        <exclusion>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
        </exclusion>
    </exclusions>
</dependency>

3. Configuring Properties

DataSource configuration : Set initialization size, min/max connections, wait time, validation query, and other pool parameters just like with C3P0 or DBCP.

WebStatFilter : Collects web‑related DB statistics such as SQL statements, execution time, request URLs, session monitoring, and table access counts.

StatViewServlet : Provides a web UI for viewing Druid statistics; configure login credentials, allowed IPs, etc.

Druid Spring Boot Starter configuration properties follow Druid's naming and can be set in the Spring Boot configuration file; defaults are applied when not specified.

application.yml example:

########## Configure Druid DataSource ##########
spring:
  datasource:
    username: xxx
    password: xxx
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/test?serverTimezone=Asia/Shanghai
    platform: mysql
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      initial-size: 5
      minIdle: 10
      max-active: 20
      max-wait: 60000
      time-between-eviction-runs-millis: 2000
      min-evictable-idle-time-millis: 600000
      max-evictable-idle-time-millis: 900000
      validationQuery: select 1
      testWhileIdle: true
      testOnBorrow: false
      testOnReturn: false
      poolPreparedStatements: true
      maxOpenPreparedStatements: 20
      keepAlive: true
      aop-patterns: "com.springboot.template.dao.*"
      filters: stat,wall,log4j2
      filter:
        stat:
          enabled: true
          db-type: mysql
          log-slow-sql: true
          slow-sql-millis: 2000
        slf4j:
          enabled: true
      web-stat-filter:
        enabled: true
        url-pattern: /*
        exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
        session-stat-enable: true
        session-stat-max-count: 1000
      stat-view-servlet:
        enabled: true
        url-pattern: /druid/*
        reset-enable: false
        login-username: root
        login-password: 123
        allow: 127.0.0.1

The configuration properties correspond to classes

com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties

and

org.springframework.boot.autoconfigure.jdbc.DataSourceProperties

.

3.1 How to Configure Filters

Enable built‑in filters via

spring.datasource.druid.filters=stat,wall,log4j2

. For custom settings, configure each filter separately, e.g.:

# 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.

4. Monitoring Pages

(1) After starting the application, visit

/druid/login.html

to log in.

(2) DataSource page shows basic information and configured filters.

(3) SQL monitoring page lists execution details for all SQL statements.

(4) URL monitoring page shows request counts and execution times for controller endpoints.

(5) Spring monitoring page records AOP‑based execution times and JDBC counts.

(6) SQL firewall page displays black‑/white‑list protection status.

(7) Session monitoring page shows session creation time, last activity, request count, etc.

(8) JSON API page returns monitoring data in JSON format.

5. SQL Monitoring

Configure

WebStatFilter

to collect all database‑related information from web requests, including SQL statements, execution time, request URLs, session stats, and table access counts.

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

6. Slow SQL Logging

Enable slow‑SQL logging to record queries that exceed a defined threshold (e.g., 2000 ms):

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

7. Spring Monitoring

Import the Spring Boot AOP starter and configure the AOP patterns to enable method‑level monitoring:

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

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

8. Removing Ads

Druid’s jar includes a

common.js

that injects an advertisement footer. Two ways to remove it:

Manually edit the jar (remove the line

// this.buildFooter();

).

Register a custom filter that intercepts

common.js

requests and strips the ad HTML via regex replacement.

@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("<a.*?banner\"></a><br/>", "");
                text = text.replaceAll("powered.*?shrek.wang</a>", "");
                response.getWriter().write(text);
            }
            @Override public void destroy() {}
        };
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(filter);
        registrationBean.addUrlPatterns(commonJsPattern);
        return registrationBean;
    }
}

9. Retrieving Druid Monitoring Data

After enabling

StatFilter

, use

DruidStatManagerFacade

to obtain runtime statistics programmatically:

@RestController
@RequestMapping("/druid")
public class DruidStatController {
    @GetMapping("/stat")
    public Object druidStat() {
        return DruidStatManagerFacade.getInstance().getDataSourceStatDataList();
    }
}
monitoringSQLConfigurationConnection PoolSpring BootDruid
Su San Talks Tech
Written by

Su San Talks Tech

Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.

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.