通过动态代理,将横切代码块与业务代码分离。
JDK 动态代理方式
public class TransactionProxyFactory<T> implements InvocationHandler {
private final T t;
public TransactionProxyFactory(T t) {
this.t = t;
}
public <E extends T> T getTarget() {
return (E) Proxy.newProxyInstance(t.getClass().getClassLoader(), t.getClass().getInterfaces(), this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
TransactionManager.beginTransaction();
Object result = method.invoke(t, args);
TransactionManager.commit();
return result;
} catch (Exception e) {
e.printStackTrace();
TransactionManager.rollback();
throw e;
}
}
}
Cglib 动态代理方式
public class TransactionCglibProxyFactory<T> implements MethodInterceptor {
private final Class<? extends T> clazz;
public TransactionCglibProxyFactory(Class<? extends T> clazz) {
this.clazz = clazz;
}
public <E extends T> T getTarget() {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(clazz);
enhancer.setCallback(this);
return (E) enhancer.create();
}
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
try {
TransactionManager.beginTransaction();
Object result = proxy.invokeSuper(obj, args);
TransactionManager.commit();
return result;
} catch (Exception e) {
e.printStackTrace();
TransactionManager.rollback();
throw e;
}
}
}
使用时调用代理对象
结合了之前写的 IoC 容器。
private final TransferService transferService = new TransactionProxyFactory<>(
(TransferService) BeanFactory.getBean("transferService")).getTarget();