1.springboot在整合druid时,首先需要在yml配置文件中加入druid的相关配置
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
#SpringBoot默认是不注入这些的,需要自己绑定
#druid数据源专有配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECt 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许报错,java.lang.ClassNotFoundException: org.apache.Log4j.Properity
#则导入log4j 依赖就行
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionoProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
2.进行druid相关的配置类的编写
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource(){
return new DruidDataSource();
}
// 后台监控:相当于web.xml,配置ServletRegistrationBean
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
// 后台登录进行账号密码配置
HashMap initParameters = new HashMap<>();
// 增加配置,登录的key是固定的,loginUsername loginPassword
initParameters.put("loginUsername","admin");
initParameters.put("loginPassword","123456");
// 允许谁可以访问,如果后面的参数为空代表谁都可以访问,指定参数只能指定的参数进行访问
initParameters.put("allow","");
// 禁止谁可以访问
// initParameters.put("koko","192.168.43.21");
bean.setInitParameters(initParameters); // 设置初始化参数
return bean;
}
// filter
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
// 可以过滤的请求
HashMap initParameters = new HashMap<>();
// 以下不进行统计
initParameters.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(initParameters);
return bean;
}
}
3.启动项目,然后被发现无法启动,会报这样一个错
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to bind properties under 'spring.datasource' to javax.sql.DataSource:
Property: spring.datasource.filters
Value: stat,wall,log4j
Origin: class path resource [application.yml]:27:14
Reason: org.apache.log4j.Logger
Action:
Update your application's configuration
4. 根据错误的指示原因,可以发现是没有导入log4j的依赖
log4j
log4j
1.2.17
5. 项目启动成功,可以进入druid的登录界面
6.在配置中设置的用户名和密码进行登录



