1.首先导入Druid依赖
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.11</version> </dependency>
2.配置数据源
创建application.yml文件
spring: datasource: username: root password: 1234 driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 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
3.创建Druid配置类
package com.peng.confing; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.support.http.StatViewServlet; import com.alibaba.druid.support.http.WebStatFilter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; import java.util.HashMap; @Configuration public class DruidConfig { @ConfigurationProperties(prefix = "spring.datasource") @Bean public DataSource druidDataSource(){ return new DruidDataSource(); } @Bean public ServletRegistrationBean a(){ ServletRegistrationBean bean=new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*"); //账号密码 HashMap initParameters = new HashMap<>(); initParameters.put("loginUsername","admin");//loginUsername固定的 initParameters.put("loginPassword","123456");//loginPassword固定的 //允许谁可以访问 initParameters.put("allow","");//允许谁可以访问 //禁止谁initParameters.put("peng","192.168.1.1")// bean.setInitParameters(initParameters);//设置初始化参数 return bean; } @Bean public FilterRegistrationBean webFilter(){ FilterRegistrationBean bean = new FilterRegistrationBean(); bean.setFilter(new WebStatFilter()); HashMap initParameters = new HashMap<>(); initParameters.put("exclusions","*.js,*.css,/druid/*"); bean.setInitParameters(initParameters); return bean; } }
4.使用 @Autowired后springboot会自动注入数据源
package com.peng; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import javax.sql.DataSource; @SpringBootTest class SpringbootDruidApplicationTests { @Autowired DataSource dataSource; @Test void contextLoads() { } }
5.启动浏览器访问http://localhost:8080/druid/登录设置的账号密码就会进入后台页面