DBCP 与 Spring Boot 集成

前面介绍了 Spring 怎样集成 DBCP,下面将通过一个简单示例演示 DBCP 和 Spring Boot 集成,然后通过 JdbcTemplate 从 MySQL 5.7.* 中获取数据库时间戳。

Maven 依赖

Spring Boot 项目的依赖如下:

<?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.7.13</version>
       <relativePath/> <!-- lookup parent from repository -->
   </parent>
   <groupId>com.hxstrive.jdbc_pool</groupId>
   <artifactId>dbcp_spring_boot</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>dbcp_spring_boot</name>
   <description>Demo project for Spring Boot</description>

   <properties>
       <java.version>8</java.version>
   </properties>

   <dependencies>
       <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
       <dependency>
           <groupId>org.apache.commons</groupId>
           <artifactId>commons-dbcp2</artifactId>
           <version>2.9.0</version>
       </dependency>

       <dependency>
           <groupId>commons-logging</groupId>
           <artifactId>commons-logging</artifactId>
           <version>1.2</version>
       </dependency>

       <!-- MySQL 驱动依赖 -->
       <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <version>5.1.38</version>
       </dependency>

       <!-- Spring Boot JDBC依赖驱动 -->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-jdbc</artifactId>
       </dependency>

       <!-- Spring Boot Web 驱动依赖 -->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-web</artifactId>
       </dependency>

       <!-- Spring Boot 开发和测试依赖 -->
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-devtools</artifactId>
           <scope>runtime</scope>
           <optional>true</optional>
       </dependency>
       <dependency>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-test</artifactId>
           <scope>test</scope>
       </dependency>
   </dependencies>

   <build>
       <plugins>
           <plugin>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-maven-plugin</artifactId>
               <configuration>
                   <excludes>
                       <exclude>
                           <groupId>org.projectlombok</groupId>
                           <artifactId>lombok</artifactId>
                       </exclude>
                   </excludes>
               </configuration>
           </plugin>
       </plugins>
   </build>

</project>

配置类

使用 @Configuration 声明一个配置类,配置 JdbcTemplate 和 DataSource(数据源),代码如下:

package com.hxstrive.pool.dbcp_spring_boot.config;

import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;

/**
* DBCP配置
* @author hxstrive.com
*/
@Configuration
public class DbcpConfig {

   /**
    * 配置 JdbcTemplate
    * @param dataSource 数据源
    * @return
    */
   @Bean
   public JdbcTemplate getJdbcTemplate(DataSource dataSource) {
       return new JdbcTemplate(dataSource);
   }

   /**
    * 配置数据源
    * @return 返回 org.apache.commons.dbcp2.BasicDataSource 数据源
    */
   @Bean
   public DataSource getDataSource() {
       BasicDataSource dataSource = new BasicDataSource();
       dataSource.setDriverClassName("com.mysql.jdbc.Driver");
       dataSource.setUrl("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false");
       dataSource.setUsername("root");
       dataSource.setPassword("aaaaaa");
       // 初始化时连接池中connection数量
       dataSource.setInitialSize(10);
       // 最小的空闲链接数量
       dataSource.setMinIdle(5);
       // 最大的空闲连接数量
       dataSource.setMaxIdle(20);
       // 最大的等待时间,单位是毫秒
       dataSource.setMaxWaitMillis(60000);
       // 是否开启自动提交,跟事务的控制有关
       dataSource.setDefaultAutoCommit(true);
       return dataSource;
   }

}

入口类

Spring Boot 项目的启动类,代码如下:

package com.hxstrive.pool.dbcp_spring_boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DbcpSpringBootApplication {

   public static void main(String[] args) {
       SpringApplication.run(DbcpSpringBootApplication.class, args);
   }

}

测试类

通过 @SpringBootTest 注解声明一个测试类,通过单元测试进行测试,代码如下:

package com.hxstrive.pool.dbcp_spring_boot;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import java.sql.Timestamp;

@SpringBootTest
class DbcpSpringBootApplicationTests {

   @Autowired
   private JdbcTemplate jdbcTemplate;

   @Test
   void contextLoads() {
       // 获取数据库当前的时间戳
       Timestamp ts = jdbcTemplate.queryForObject("select CURRENT_TIMESTAMP() as ct", Timestamp.class);
       System.out.println("当前时间:" + ts);
   }

}

运行测试类,输出如下:

... 省略 ...
 .   ____          _            __ _ _
/\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/  ___)| |_)| | | | | || (_| |  ) ) ) )
 '  |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot ::               (v2.7.13)

2023-07-06 13:21:37.360  INFO 16968 --- [           main] c.h.p.d.DbcpSpringBootApplicationTests   : Starting DbcpSpringBootApplicationTests using Java 1.8.0_45 on hxstrive with PID 16968 (started by Administrator in D:\~my_workspace\jdbc_pool\dbcp_spring_boot)
2023-07-06 13:21:37.364  INFO 16968 --- [           main] c.h.p.d.DbcpSpringBootApplicationTests   : No active profile set, falling back to 1 default profile: "default"
2023-07-06 13:21:42.400  INFO 16968 --- [           main] c.h.p.d.DbcpSpringBootApplicationTests   : Started DbcpSpringBootApplicationTests in 5.848 seconds (JVM running for 9.541)
当前时间:2023-07-06 13:21:43.0

Process finished with exit code 0
说说我的看法
全部评论(
没有评论
关于
本网站属于个人的非赢利性网站,转载的文章遵循原作者的版权声明,如果原文没有版权声明,请来信告知:hxstrive@outlook.com
公众号