通过动态代理,将横切代码块与业务代码分离。

JDK 动态代理方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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 动态代理方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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 容器。

1
2
3
private final TransferService transferService = new TransactionProxyFactory<>(
(TransferService) BeanFactory.getBean("transferService")).getTarget();