一 说明
在项目中,当使用多数据源的时候,业务复杂的时候,会出现数据源A的方法里面嵌套调用数据源B的方法,这里面涉及到一个事务切换的问题,一般的方法没问题,根据通过aop注解在方法上通过加注解标识指定对应的数据源同时切换到对应的事务管理器,但是有这样的场景就不适用了,比如:数据源A的一个方法里面有调用数据源B的私有方法,这样的情况,如果还是通过方法上的注解就不行了,数据源B的方法也会走数据源A的事务管理器,这样的问题怎么解决呢,答案是:通过spring aop类里面的AopContext类获取当前类的代理对象,这样就能切换对应的事务管理器了,具体做法如下:
(1) 配置类上加 @EnableAspectJAutoProxy(exposeProxy = true)
a)也可以在 applicationContext.xml文件中配置如下:
<!-- 开启暴露Aop代理到ThreadLocal支持 -->
<aop:aspectj-autoproxy expose-proxy="true"/>
(2).在需要切换的地方获取代理对象,再调用对应的方法,如下:
((PercentageRepository) AopContext.currentProxy()).findByPost(percentagePost);
说明 PercentageRepository 自己业务类,findByPost(...) 业务方法
(3).注意,这里需要被代理对象使用的方法必须是public类型的方法,不然获取不到代理对象,会报下面的错误:
java.lang.IllegalStateException: Cannot find current proxy: Set 'exposeProxy' property on Advised to 'true' to make it available.
(4).通过查看AopContext.class类的源代码得知,调用获取代理对象的方法必须是public修饰的,如下源代码:
public static Object currentProxy() throws IllegalStateException {
Object proxy = currentProxy.get();
if (proxy == null) {
throw new IllegalStateException(
"Cannot find current proxy: Set 'exposeProxy' property on Advised to 'true' to make it available.");
}
return proxy;
}
static Object setCurrentProxy(Object proxy) {
Object old = currentProxy.get();
if (proxy != null) {
currentProxy.set(proxy);
}
else {
currentProxy.remove();
}
return old;
}