1.首先添加如下依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
2.在application.properties中添加如下内容
#MySQL8.0以上为com.mysql.cj.jdbc.Driver,5或者6版本的不用加cj
spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.druid.url=jdbc:mysql://localhost:3306/xxx(数据库名)?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.druid.username=root
spring.datasource.druid.password=xxxxx #数据库密码
spring.datasource.druid.initial-size=5
spring.datasource.druid.max-active=20
spring.datasource.druid.max-wait=10000
spring.datasource.druid.min-idle=5
spring.datasource.druid.validation-query=SELECT 'x'
spring.datasource.druid.time-between-eviction-runs-millis=60000
spring.datasource.druid.min-evictable-idle-time-millis=300000
#statFilter配置
spring.datasource.druid.filter.stat.log-slow-sql=true
#statFilter配置
spring.datasource.druid.filter.stat.slow-sql-millis=200
#statFilter配置
spring.datasource.druid.filter.stat.merge-sql=true
3.在下创建一个config包然后再创建一个DruidConfig类,图中已经创建完成
类中写如下内容
@Configuration
public class DruidConfig {
@Bean
public ServletRegistrationBean servletRegistrationBean(){
return new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
}
}
然后导入该导入的包即可
如果提示如下错误
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dataSource':
Unsatisfied dependency expressed through field 'basicProperties'; nested exception is
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'spring.datasource-
org.springframework.boot.autoconfigure.jdbc.DataSourceProperties': Instantiation of bean failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springfram
那么需要再在pom.xml中添加如下依赖(我的数据库是8版本以上的)
<!--https://mvnrepository.com/artifact/mysql/mysql-connector-java-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.13</version>
</dependency>
<!--dataSource这个Bean找不到的话加上面和下面的依赖就可以用了-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
再次运行,发现不报错误了,运行成功