SpringBoot整合Druid(阿里巴巴)数据源
(1)、添加相关依赖
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-jdbc</artifactId> 4 </dependency> 5 6 <dependency> 7 <groupId>mysql</groupId> 8 <artifactId>mysql-connector-java</artifactId> 9 <version>8.0.14</version> 10 </dependency> 11 12 <dependency> 13 <groupId>com.alibaba</groupId> 14 <artifactId>druid</artifactId> 15 <version>1.1.12</version> 16 </dependency>
(2)、配置配置文件
1 spring.datasource.username=root 2 spring.datasource.password=123456 3 spring.datasource.url=jdbc:mysql://localhost:3306/JdbcDemo?serverTimezone=UTC 4 spring.datasource.driver-class-name=com.mysql.jdbc.Driver 5 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
(3)将配置文件自定义属性和自定义数据源绑定(我配置文件中没有自定义属性),配置Druid监控
1 package cn.coreqi.config; 2 3 import com.alibaba.druid.pool.DruidDataSource; 4 import com.alibaba.druid.support.http.StatViewServlet; 5 import com.alibaba.druid.support.http.WebStatFilter; 6 import org.springframework.boot.context.properties.ConfigurationProperties; 7 import org.springframework.boot.web.servlet.FilterRegistrationBean; 8 import org.springframework.boot.web.servlet.ServletRegistrationBean; 9 import org.springframework.context.annotation.Bean; 10 import org.springframework.context.annotation.Configuration; 11 12 import javax.sql.DataSource; 13 import java.util.Arrays; 14 import java.util.HashMap; 15 import java.util.Map; 16 17 @Configuration 18 public class DruidConfig { 19 @Bean 20 @ConfigurationProperties(prefix = "spring.datasource") 21 public DataSource druid(){ 22 return new DruidDataSource(); 23 } 24 25 //配置Druid监控 26 27 //配置Druid管理后台的Servlet 28 //还记得如何在SpringBoot中注册Servlet吗? 29 @Bean 30 public ServletRegistrationBean statViewServlet(){ 31 ServletRegistrationBean registrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*"); 32 Map<String,String> initParams = new HashMap<>(); 33 initParams.put("loginUsername","admin"); 34 initParams.put("loginPassword","admin"); 35 registrationBean.setInitParameters(initParams); 36 return registrationBean; 37 } 38 39 //配置Druid监控的Filter 40 //还记得如何在SpringBoot中注册Filter吗? 41 @Bean 42 public FilterRegistrationBean webStatFilter(){ 43 FilterRegistrationBean registrationBean = new FilterRegistrationBean(new WebStatFilter()); 44 Map<String,String> initParams = new HashMap<>(); 45 initParams.put("exclusions","*.js,*.css,/druid/*"); 46 registrationBean.setInitParameters(initParams); 47 registrationBean.setUrlPatterns(Arrays.asList("/*")); 48 return registrationBean; 49 } 50 }
(4)访问http://localhost:8080/druid