Using Alibaba Druid Connection Pool with Spring Boot: Dependencies, Configuration, Monitoring, and Customization
This article explains how to integrate Alibaba's Druid database connection pool into a Spring Boot application, covering Maven dependencies, YAML configuration, built‑in filters, monitoring pages, ad removal techniques, and programmatic access to Druid statistics for comprehensive backend performance management.
Druid is a Java‑based database connection pool developed by Alibaba, offering extensive monitoring and extensibility features that surpass other pools such as HikariCP, C3P0, and DBCP.
To add Druid to a Spring Boot project, include the following Maven dependencies:
<!-- Alibaba Druid 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>
<!-- Exclude default HikariCP when using MyBatis -->
<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>Configure the datasource and Druid‑specific properties in application.yml:
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
wall:
enabled: true
db-type: mysql
config:
delete-allow: false
drop-table-allow: false
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.1Druid provides several built‑in filters such as StatFilter for statistics, WallFilter for SQL injection protection, and Log4j2Filter for logging; they can be enabled via the filters property or configured individually as shown above.
After starting the application, the monitoring UI is accessible at /druid/login.html. The UI includes pages for datasource overview, SQL execution statistics, URL access stats, session details, and a JSON API.
To remove the default Alibaba advertisement displayed at the bottom of the Druid UI, either manually comment out the this.buildFooter(); line in the common.js bundled inside the Druid JAR, or register a custom filter that rewrites the JavaScript response, as illustrated in the following Spring configuration:
@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;
}
}Programmatic access to Druid statistics can be achieved via DruidStatManagerFacade. For example, a simple REST controller can expose the datasource statistics as JSON:
@RestController
@RequestMapping("/druid")
public class DruidStatController {
@GetMapping("/stat")
public Object druidStat() {
return DruidStatManagerFacade.getInstance().getDataSourceStatDataList();
}
}All configuration properties are also documented in the classes
com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatPropertiesand
org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Architect's Tech Stack
Java backend, microservices, distributed systems, containerized programming, and more.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
