在项目中使用mybatis与spring进行开发的时候,由于使用到多数据源,在进行依赖注入的时候发生如下异常。
Caused by:
org.springframework.beans.factory.BeanCreationException:
Could not autowire method:
public final void org.mybatis.spring.support.
SqlSessionDaoSupport.setSqlSessionFactory
(org.apache.ibatis.session.SqlSessionFactory);
nested exception is org.springframework.beans.factory.
NoSuchBeanDefinitionException:
No unique bean of type [org.apache.ibatis.session.SqlSessionFactory] is defined:
expected single matching bean but found 2: [sqlSessionFactory1, sqlSessionFactory2]
主要是项目中一个数据源的Dao处理以及上层使用的注解方式,而另一个数据源全部是通过配置文件来处理的。
后来发现是自动扫描出现的问题,将自动扫描代码的annotation-config设置为false,如下所示:
<context:component-scan base-package="com.xxx.xxx"
annotation-config="false" />
以上情况是dao代码中均使用org.mybatis.spring.SqlSessionFactoryBean配置造成的。
如果dao代码中使用SqlSessionTemplate,则不需要调整上面所述的自动注解的问题,代码如下:
<bean id="sqlSessionTemplate1"
class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="cspSqlSessionFactory" />
</bean>