使用工具SpringToolSuite4

首先在spring项目中添加依赖
添加两个依赖 --> mysql依赖和spring-jdbc依赖
添加方式一:
创建项目时添加:
image.png

添加方式二:
通过pom文件将两个依赖添加:
Mysql依赖 ↓

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

JDBC依赖 ↓

<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>

配置spring项目创建时rource目录中的 application.properties
连接数据库的url,username,password

spring.datasource.url=jdbc:mysql:///dbgoods?serverTimezone=GMT%2B8&characterEnconding=utf8
spring.datasource.username=root
spring.datasource.password=root

最后,编写测试类DataSourceTest从池中获取连接(Connection)
建立测试类,在启动类或其子包下
image.png

package com.cy.datasource;
import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;


@SpringBootTest
public class DataSourceTests {

    @Autowired
    private DataSource dataSource;
    
    @Test
    void testConnection01() throws SQLException {
        System.out.println(dataSource.getConnection());
    }
}

连接成功。

问题思考:
一:已知此处的DataSource是接口,那dataSource.getConnection()时,spring框架注入的对象是谁?

@Autowired
private DataSource dataSource;

@Test
void testConnection01() throws SQLException {
    System.out.println(dataSource.getConnection());
}

答:此处的对象是HikariDataSource对象,可以通过

System.out.println(dataSource.getClass().getName());

来获取对象的名称


安德路西
4 声望3 粉丝

下一篇 »
初识GC