expected single matching bean but found 2
阿新 • • 發佈:2017-11-01
scanner tac ebean col myba ram figure fin expressed
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會有重復註冊的現象,就會出現文章開頭的錯誤了。
expected single matching bean but found 2