zoukankan      html  css  js  c++  java
  • 多个@bean无法通过@resource注入对应的bean(org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available: expected single matching bean but found )

    一、异常

    org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'javax.sql.DataSource' available: expected single matching bean but found 2: masterDataSource,slaveDataSource

    二、场景分析

    看异常提示这个类型”javax.sql.DataSource“的bean期待一个单例bean但是发现了2个:masterDataSource,slaveDataSource。看打印的堆栈:

     如上,我们发现有个DataSourceInitializer.init方法追踪进去:

    这里就给了我们一个灵感,DataSourceInitializer这个数据源初始化是spring boot自动配置类启动的。如下图

    继续追踪异常:最终定位在DefaultListableBeanFactory.resolveNamedBean()中如下代码块:

    如上图第一,第二个箭头分别取@Primary和@Priority2种注解注释的bean,只要存在,就可以获取bean并返回。

    三、解决方案

    1. 在其中一个bean上加@Primary,使得自动配置时不报错。

    1 @ConfigurationProperties(prefix = "study.datasource.master")
    2 @Bean(name = "masterDataSource")
    3 @Primary
    4 public DataSource masterDataSource() {
    5 }

    2. 在启动类注解:

    @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})

  • 相关阅读:
    Xamarin.Forms添加启动动画
    asp.netcore mvc Json中文乱码
    The database provider attempted to register an implementation of the 'IRelationalTypeMappingSource' service.
    阻塞线程的办法
    日常学习东西
    第三方框架的学习经验
    业余时间作为学习
    UI卡顿以及解决的办法
    Kotlin语言学习
    这两个面试经常被问到两个常见算法
  • 原文地址:https://www.cnblogs.com/dennyzhangdd/p/10843100.html
Copyright © 2011-2022 走看看