一、问题描述
最近重新创建项目,在配置数据库进行连接测试时犯了十分低级的错误,特此记录一下。
具体错误是:Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type ‘javax.sql.DataSource’ available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
就是说DataSource的bean注入失败了
二、场景还原
刚创建完项目顺手进行数据库连接测试,每个文件只保留相关代码
1. pom.xml
<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>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<version>2.7.18</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<version>2.7.18</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
<version>5.1.47</version>
</dependency>
</dependencies>
</project>
2. application.yml
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/mysql?useSSL=false
username: root
password: root
3. 临时启动类
@SpringBootApplication
public class ApplicationTests {
}
这里还遇上前一个错误【沉浸式解决问题】java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use
4. 测试类
顺理成章的就想用DataSource测试数据库连接,就搞出了问题,刚学完肯定不会出这种错,哈哈
@SpringBootTest
public class MysqlTest {
@Autowired
private DataSource dataSource; // 自动注入数据源
@Test
void test1() throws SQLException {
if (dataSource != null) {
Connection connection = dataSource.getConnection();
if (connection != null) {
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT 1");
if (rs.next()) {
int result = rs.getInt(1);
if (result == 1) {
System.out.println("数据库配置测试通过!");
}else {
System.out.println("查询返回值错误,预期 1,实际 " + result);
}
}else {
System.out.println("查询无结果,数据库状态异常");
}
}else {
System.out.println("数据库连接失败");
}
}else {
System.out.println("创建数据源对象失败");
}
}
}
就这样,test1()一运行就会报题目所说的错
三、原因分析
原因就是DataSource并不会自动装配yml中的数据库配置,缺少依赖,平常创建项目都是常用依赖一次性都复制过来,久而久之,导致很多基础的细节就忽略了。
Spring Boot 的自动配置是基于条件的。对于数据源的自动配置,当检测到数据库驱动和相关的 JDBC Starter 时,会自动配置 DataSource Bean。
找原因的过程中一直觉得是缺什么配置,就是忘记缺依赖,因为如果是配置错误应该报的是具体错误原因,bean未注入很明显是对象直接无法生成。
四、解决方案
在pom文件中添加JDBC Starter的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
问题是解决了,但是查看以前的项目,并没有显示的声明这一依赖,为什么可以呢
最开始没有找到问题原因,想着DataSource注入不成功,用平常常用的mybatis-plus查询试试,加入mybatis-plus-boot-starter
这一依赖后,发现之前的问题没有了,在找到这一原因后查看依赖树即可看到,mybatis-plus-boot-starter
中依赖了spring-boot-starter-jdbc
,真相大白。