通过SpringBoot配置文件配置Druid数据源
在SpringBoot 1.X 中,spring-boot-starter-jdbc启动器中默认使用的是org.apache.tomcat.jdbc.pool.DataSource作为数据源
在SpringBoot 2.X 中,spring-boot-starter-jdbc启动器中默认使用的是com.zaxxer.hikari.HikariDataSource作为数据源
引入坐标依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.zjw</groupId>
<artifactId>springbootjdbc</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springbootjdbc</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--Thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!--jdbc-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.15</version>
</dependency>
<!--druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
配置application.properties文件
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.234.128/sb?useSSL=false&serverTimeZone=Shanghai/Asia
spring.datasource.username=root
spring.datasource.password=a@123456
#指定为Druid数据源,默认为HikariDataSource数据源
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
新建一个controller观察使用的是哪一个数据源
package com.zjw.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import javax.annotation.Resource;
import javax.sql.DataSource;
@Controller
public class UsersController {
@Resource
private DataSource dataSource;
@GetMapping("/showInfo")
public String showInfo(){
//观察使用的是哪个数据源
System.out.println(this.dataSource.getClass());
return "OK";
}
}
打印结果:
class com.alibaba.druid.pool.DruidDataSource
---------------
我每一次回头,都感觉自己不够努力,所以我不再回头。
---------------