expected single matching bean but found 2,matchingbean

來源:互聯網
上載者:User

expected single matching bean but found 2,matchingbean

1 org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accountAction': Unsatisfied dependency expressed through field 'accountService'; nested exception is org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.xxx.IAccountService' available: expected single matching bean but found 2: accountServiceImpl,IAccountService

讓我很是疑惑,為什麼會產生這個錯誤。

查資料很多說是一個介面有兩個實作類別,在引用的時候單純的使用Autowire就會出現上述錯誤。但是我看了一下項目中的代碼,沒有出現這種情況。

嘗試過很多次後,找到問題了,是因為MyBatis的MapperScannerConfigurer的配置引起的。

項目中出了MapperScannerConfigurer的包名掃描配置以外,還有一處Spring的配置, <context:component-scan base-package="com.xxx.yyy" /> 

MyBatis的MapperScannerConfigurer 的配置:

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">   <property name="basePackage" value="com.xxx.yyy" />   <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /></bean>

修改為:

<context:component-scan base-package="com.xxx.yyy" /><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">   <property name="basePackage" value="com.xxx.yyy.**.dao" />   <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /></bean>

解決問題。

跟了一下MapperScannerConfigurer 原始碼,MapperScannerConfigurer 會把 配置的basePackage下面的mapper介面掃描到,並將他們註冊到spring容器中去。


如果配置的路徑範圍過大,spring base-package 和 mybatis basePackage 下面的bean會有重複註冊的現象,就會出現文章開頭的錯誤了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.