为什么数据源不能在spring boot应用程序中自动连接?

为什么数据源不能在spring boot应用程序中自动连接?,spring,spring-boot,datasource,Spring,Spring Boot,Datasource,我知道,如果在应用程序中设置了相关配置,spring boot将自动创建数据源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.passw

我知道,如果在
应用程序中设置了相关配置,spring boot将自动创建
数据源
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数据源被注释掉,将打印Bean信息:

org.apache.tomcat.jdbc.pool.DataSource@1800a575{ConnectionPool[defaultAutoCommit=null; defaultReadOnly=null; ....}
所以我认为SpringBoot真的创造了Bean

但若使用@Autowried DataSource,则会出现异常,抱怨并没有这样的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
),而不是该接口的特定实现。

请发布不起作用的完整案例,而不仅仅是一个片段。另外,您应该使用
javax.sql.DataSource
而不是特定的tomcat类型。谢谢。我重新编辑了帖子并添加了完整的代码。啊,戴纳姆,你明白了。在我“import javax.sql.DataSource”而不是“import org.apache.tomcat.jdbc.pool.DataSource;”之后,就没有问题了!如果我使用特定的tomcat类型,但是getBean()是可以的,那么您能再解释一下为什么自动连线失败吗?谢谢!是的,这是根本原因。谢谢