SpringBoot不要从yml配置创建数据源

时间:2019-11-20 11:28:09

标签: java spring spring-boot jdbc datasource

application.yml中,我定义了数据源:

spring:
  datasource:
    driver-class-name: ru.yandex.clickhouse.ClickHouseDriver
    username: default
    url: jdbc:clickhouse://localhost:8123/default

我也创建了一些配置:

@Configuration
@AutoConfigureAfter(DataSourceAutoConfiguration.class)
public class MyConfig {

    @Getter
    private ReportRoutingDataSource dataSourceStorage = new ReportRoutingDataSource();

    @Bean("dataSourceStorage")
    public DataSource dataSource(@Qualifier("dataSource") DataSource dataSource) {
        dataSourceStorage.setDefaultTargetDataSource(dataSource);
        dataSourceStorage.setTargetDataSources(resolvedDataSources());
        dataSourceStorage.afterPropertiesSet();
        return dataSourceStorage;
    }

    @Bean
    public Map<Object, Object> resolvedDataSources() {
        //some another logic;
    }
}

ReportRoutingDataSource:

public class ReportRoutingDataSource extends AbstractRoutingDataSource {

    @Override
    protected Object determineCurrentLookupKey() {
        return RequestContext.getKeyToChoseDataSource();
    }

}

我想使用自动配置从yml文件创建默认数据源,并将其添加到dataSourceStorage.setDefaultTargetDataSource(dataSource)作为默认数据源。

我设置了注释@AutoConfigureAfter(DataSourceAutoConfiguration.class),该配置是在自动配置标准数据源之后创建的。

但是,当我启动我的应用程序时,出现错误:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dataSourceStorage' defined in class path resource [com/example/spring/MyConfig.class]: Unsatisfied dependency expressed through method 'dataSource' parameter 0; nested exception is 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.Qualifier(value=dataSource)}

但是,为什么呢?我该如何解决?

1 个答案:

答案 0 :(得分:0)

将您的“数据源”方法替换为

@Bean("dataSourceStorage")
public ReportRoutingDataSource reportRoutingDataSource (@Autowired("dataSource") DataSource dataSource) {
    ReportRoutingDataSource dataSourceStorage = new ReportRoutingDataSource();
    dataSourceStorage.setDefaultTargetDataSource(dataSource);
    dataSourceStorage.setTargetDataSources(resolvedDataSources());
    dataSourceStorage.afterPropertiesSet();
    return dataSourceStorage;
}

并为ReportRoutingDataSource删除@Getter。