junit 寫單元測試的時候,因爲項目本身是多數據源的所以在寫測試的時候一直提示
No qualifying bean of type [javax.sql.DataSource] is defined: expected single matching bean but found 3: xx-dataSource xx-dataSource xx-dataSource
spring 在注入的時候無非確認採用哪個數據源
需要指定使用數據源
@Override
@Resource(name = "xx-dataSource")
public void setDataSource(DataSource dataSource) {
// TODO Auto-generated method stub
super.setDataSource(dataSource);
}
昨天又進行了實驗debug跟蹤,發現進行數據源的指定後並沒有將本類中所有操作固定爲該數據源,對mapper調用仍然使用的是該mapper所屬數據源。
換句話說
部分配置文件
<!-- mapperScannerConfigurer -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.acedata.carcoo.mapper.beforeLoan"></property>
<property name="sqlSessionFactoryBeanName" value="beforeLoan-sqlSessionFactory" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.acedata.carcoo.mapper.afterLoan"></property>
<property name="sqlSessionFactoryBeanName" value="afterLoan-sqlSessionFactory" />
</bean>
com.acedata.carcoo.mapper.beforeLoan 下的usermapper使用數據源爲beforeLoan
com.acedata.carcoo.mapper.afterLoan 下的loanmapper使用數據源爲afterLoan
即使在 @Resource(name = "beforeLoan-dataSource")
在測試期間有個問題一直困擾好長時間花費了一天多才找到問題。
在aop在進行增強處理的時候設置的是service實現類但是在junit測試的時候注入的是mapper所以其實spring的事務是沒有生效的。走入了一個誤區,一直在找的是多數據源進行測試的時候爲什麼事務沒有生效。所以耽誤了很長時間。
另外需要注意的一點是多數據源在配置多個數據源時,設置多個事務,同時也需要設置多個增強處理Advice