引入pom

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-jdbc</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>com.alibaba</groupId>
  7. <artifactId>druid</artifactId>
  8. <version>1.1.14</version>
  9. </dependency>
  10. <dependency>
  11. <groupId>mysql</groupId>
  12. <artifactId>mysql-connector-java</artifactId>
  13. <scope>runtime</scope>
  14. </dependency>

application.yml

  1. spring:
  2. datasource:
  3. driver-class-name: com.mysql.cj.jdbc.Driver
  4. type: com.alibaba.druid.pool.DruidDataSource
  5. username: mytest
  6. password: mytest
  7. url: jdbc:mysql://192.168.0.12:3306/mytest?serverTimezone=GMT%2B8
  8. initialSize: 8
  9. minIdle: 5
  10. maxActive: 20
  11. maxWait: 60000
  12. timeBetweenEvictionRunsMillis: 60000
  13. minEvictableIdleTimeMillis: 300000
  14. validationQuery: SELECT 1 FROM DUAL
  15. testWhileIdle: true
  16. testOnBorrow: false
  17. testOnReturn: false
  18. poolPreparedStatements: true

创建一个durid的配置类(别忘记 @Bean 加入容器)

  1. import com.alibaba.druid.pool.DruidDataSource;
  2. import org.springframework.boot.context.properties.ConfigurationProperties;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.context.annotation.Configuration;
  5. import javax.sql.DataSource;
  6. @Configuration
  7. public class DruidConfig {
  8. @ConfigurationProperties(prefix = "spring.datasource")
  9. @Bean
  10. public DataSource dataSource(){
  11. return new DruidDataSource();
  12. }
  13. }

测试类

  1. import org.junit.jupiter.api.Test;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.boot.test.context.SpringBootTest;
  4. import javax.sql.DataSource;
  5. import java.sql.Connection;
  6. import java.sql.SQLException;
  7. @SpringBootTest
  8. class SpringbootApplicationTests {
  9. @Autowired
  10. DataSource dataSource;
  11. @Test
  12. void contextLoads() throws SQLException {
  13. System.out.println(dataSource.getClass());
  14. Connection connection = dataSource.getConnection();
  15. System.out.println(connection);
  16. connection.close();
  17. }
  18. }

打断点

  1. initialSize=8

整合成功