思路参照 spring读写分离 - 事务配置篇(转) ,不过是基于@Transactional判断,所以每个需要事务的方法上都必须添加上这个注解,这里直接贴出代码:
配置文件:
多数据源配置:
<bean id="dataSource"
class="com.lmiky.platform.database.datasource.DynamicDataSource">
<property name="readDataSources">
<list>
<ref bean="readDataSource1" />
<ref bean="readDataSource2" />
</list>
</property>
<property name="writeDataSource" ref="writeDataSource" />
</bean>
数据源拦截器:
<bean id="dateSourceAspect"
class="com.lmiky.platform.database.datasource.DateSourceAspect" />
<aop:config expose-proxy="true">
<aop:aspect ref="dateSourceAspect" order="0">
<aop:pointcut id="dateSourcePointcut"
expression="execution(* com.lmiky..service.impl..*.*(..))"/>
<aop:around pointcut-ref="dateSourcePointcut" method="determineReadOrWriteDB" />
</aop:aspect>
</aop:config>
要保证让这个拦截在事务的拦截器之前,否则如果spring先拦截事务的话,就不会起效了。可以用order设的值来排序,或者把这个配置的代码放在跟事务配置的代码同一个页面,并且放在事务配置代码的前面,spring是按代码顺序来执行的。
其他的跟单个数据源配置一样。
java代码:
package com.lmiky.platform.database.datasource;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
i