com.jquicker.persistent.rdb.tx.TransactionAdvice Maven / Gradle / Ivy
package com.jquicker.persistent.rdb.tx;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import com.jquicker.annotation.tx.Transactional;
import com.jquicker.aop.Advice;
/**
* @author OL
*/
public class TransactionAdvice implements Advice {
private Object target; // 将要创建动态代理的对象(@Service)
private TransactionAspect aspect; // 事务切面
public TransactionAdvice(Object target, TransactionAspect aspect) {
super();
this.target = target;
this.aspect = aspect;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
// 判断是否需要开启事务
Advice advice = (Advice) Proxy.getInvocationHandler(proxy);
Class> clazz = advice.getTarget().getClass();
Method m = clazz.getMethod(method.getName(), method.getParameterTypes());
boolean hasTx = clazz.isAnnotationPresent(Transactional.class) ||
m.isAnnotationPresent(Transactional.class);
boolean isOpen = aspect.isOpen();
if(hasTx && !isOpen){
aspect.start(); // 开启事务
}
try {
result = method.invoke(target, args);
if(hasTx && !isOpen){
aspect.commit();
}
} catch (Exception e) {
if(hasTx && !isOpen){
aspect.rollback(m, e);
}
throw e;
} finally {
if(hasTx && !isOpen){
aspect.close();
}
}
return result;
}
@Override
public Object getTarget() {
return target;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy