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會有重複註冊的現象,就會出現文章開頭的錯誤了。