SpringBoot整合Druid(阿里巴巴)数据源

时间:2022-04-18 09:57:54

(1)、添加相关依赖

         <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.14</version>
</dependency> <dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>

(2)、配置配置文件

 spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/JdbcDemo?serverTimezone=UTC
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource

(3)将配置文件自定义属性和自定义数据源绑定(我配置文件中没有自定义属性),配置Druid监控

 package cn.coreqi.config;

 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.Arrays;
import java.util.HashMap;
import java.util.Map; @Configuration
public class DruidConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource druid(){
return new DruidDataSource();
} //配置Druid监控 //配置Druid管理后台的Servlet
//还记得如何在SpringBoot中注册Servlet吗?
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
Map<String,String> initParams = new HashMap<>();
initParams.put("loginUsername","admin");
initParams.put("loginPassword","admin");
registrationBean.setInitParameters(initParams);
return registrationBean;
} //配置Druid监控的Filter
//还记得如何在SpringBoot中注册Filter吗?
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean(new WebStatFilter());
Map<String,String> initParams = new HashMap<>();
initParams.put("exclusions","*.js,*.css,/druid/*");
registrationBean.setInitParameters(initParams);
registrationBean.setUrlPatterns(Arrays.asList("/*"));
return registrationBean;
}
}

(4)访问http://localhost:8080/druid