Databases 16 min read

Master Druid: Configure, Monitor, and Optimize Java Database Connections in Spring Boot

This guide explains Druid—Alibaba's Java database connection pool—covering its core concepts, Maven dependencies, property configuration, built‑in filters, SQL and slow‑SQL monitoring, Spring AOP integration, ad removal, and how to retrieve runtime statistics via DruidStatManagerFacade, all with complete code examples.

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

Druid is Alibaba's Java database connection pool designed for monitoring and extensibility, offering features such as StatFilter, WallFilter, and log4j2 integration.

Basic concepts

Add dependencies

Configure related properties

SQL monitoring

Slow SQL recording

Spring monitoring

Remove advertisement

Obtain Druid monitoring data

1. Add Maven dependencies

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

<!-- MySQL 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>

<!-- MyBatis (excludes default HikariCP) -->
<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>

2. Configure Druid datasource properties (application.yml)

########## DataSource configuration (Druid) ##########
spring:
  datasource:
    username: xxx
    password: xxx
    driver-class-name: com.mysql.cj.jdbc.Driver   # MySQL 8 driver
    url: jdbc:mysql://127.0.0.1:3306/test?serverTimezone=Asia/Shanghai
    platform: mysql
    type: com.alibaba.druid.pool.DruidDataSource

    druid:
      # Connection pool settings
      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
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      pool-prepared-statements: true
      max-open-prepared-statements: 20
      keep-alive: true
      aop-patterns: "com.springboot.template.dao.*"

      # Enable built‑in filters (Stat, Wall, Log4j2)
      filters: stat,wall,log4j2
      filter:
        stat:
          enabled: true
          db-type: mysql
          log-slow-sql: true
          slow-sql-millis: 2000
        wall:
          enabled: true
        log4j2:
          enabled: true

      # WebStatFilter for web request monitoring
      web-stat-filter:
        enabled: true
        url-pattern: "/*"
        exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
        session-stat-enable: true
        session-stat-max-count: 1000

      # StatViewServlet (monitoring UI)
      stat-view-servlet:
        enabled: true
        url-pattern: /druid/*
        reset-enable: false
        login-username: root
        login-password: 123
        allow: 127.0.0.1
        deny:

The above configuration mirrors the property names defined in

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

and

org.springframework.boot.autoconfigure.jdbc.DataSourceProperties

.

3. Configure filters

Enable built‑in filters via spring.datasource.druid.filters=stat,wall,log4j2. For custom settings, define them in application.yml as shown above. Example of configuring StatFilter and WallFilter:

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

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

4. Remove Druid UI advertisement

The Druid monitoring page includes an advertisement injected by common.js. You can remove it either by commenting the line // this.buildFooter(); inside the JAR or by registering a custom filter that rewrites the JS response.

@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");
        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;
    }
}

5. SQL monitoring and slow‑SQL logging

Enable StatFilter to collect SQL execution data and configure slow‑SQL thresholds (e.g., 2000 ms). When a query exceeds the threshold, it is logged.

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

6. Spring AOP monitoring

Import spring-boot-starter-aop and set spring.datasource.druid.aop-patterns to the packages you want to monitor (e.g., com.springboot.template.dao.*).

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

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

7. Accessing Druid monitoring UI

After starting the application, visit /druid/login.html and log in with the configured username and password. The UI provides pages for datasource information, SQL statistics, URL statistics, session monitoring, and JSON API.

8. Retrieve 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 method returns a list of DataSourceStatData objects containing runtime metrics such as active connections, SQL execution counts, and latency.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javaSpring BootDruidDatabase Connection PoolSQL Monitoring
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

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.