gpt4 book ai didi

spring - 为什么 DataSource 无法在 Spring Boot 应用程序中 Autowiring ?

转载 作者:行者123 更新时间:2023-12-02 11:47:15 26 4
gpt4 key购买 nike

我知道如果在application.properties中设置了相关配置,Spring Boot会自动创建一个dataSource Bean,例如:

spring.datasource.url = jdbc:mysql://192.168.10.103:3306/hms?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
spring.datasource.password=test@123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

申请代码:

package com.synline.mdataserver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.apache.tomcat.jdbc.pool.DataSource;

@SpringBootApplication
public class Application implements CommandLineRunner {

@Autowired
AnnotationConfigApplicationContext context;

/*@Autowired
DataSource dataSource;*/

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

@Override
public void run(String... args) throws Exception {
DataSource dataSource = (DataSource)context.getBean("dataSource");
System.out.println(dataSource);

while (true) {
Thread.sleep(5000);
}

}
}

如果@Autowired DataSource被注释掉,则会打印Bean信息:

org.apache.tomcat.jdbc.pool.DataSource@1800a575{ConnectionPool[defaultAutoCommit=null; defaultReadOnly=null; ....}

所以我认为 Spring Boot 真正创建了 Bean。

但是如果使用@Autowried DataSource,则会发生异常,提示No Such Bean

Error creating bean with name 'application': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.apache.tomcat.jdbc.pool.DataSource com.synline.mdataserver.Application.dataSource; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.apache.tomcat.jdbc.pool.DataSource] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

最佳答案

您的变量应声明为标准 JDBC 数据源(即 javax.sql.DataSource),而不是该接口(interface)的特定实现。

关于spring - 为什么 DataSource 无法在 Spring Boot 应用程序中 Autowiring ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33071810/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com