为什么DataSource无法在Spring启动应用程序中自动装配?

Zhe*_*Zhu 6 spring datasource spring-boot

我知道dataSource如果设置相关配置,spring boot会自动创建一个Bean application.properties,如:

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
Run Code Online (Sandbox Code Playgroud)

申请代码:

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);
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

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

org.apache.tomcat.jdbc.pool.DataSource@1800a575{ConnectionPool[defaultAutoCommit=null; defaultReadOnly=null; ....}
Run Code Online (Sandbox Code Playgroud)

所以我认为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)}
Run Code Online (Sandbox Code Playgroud)

JB *_*zet 6

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