本帖最后由 Mylo 于 2018-8-24 19:54 编辑
思路,给所有的受管理的类的方法添加实务 那么 我们就在调用这个对象之前,先用动态代理去管理它,在使用方法的时候,通过代理对象去执行方法即可 package test.mylo.factory;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class MyFactory {
/**
* 主要是通过动态代理的方式去给service层的方法添加事物控制
* 思路,给所有的受管理的类的方法添加实务 那么 使用动态代理就可以实现
* 这里主要是模拟
*
* */
public static Object getObj(Object obj){
Object proxy = Proxy.newProxyInstance(MyFactory.class.getClassLoader(), obj.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//开启事物
System.out.println("开启事务");
Object invoke = null;
try {
invoke = method.invoke(obj, args);
System.out.println("事务提交");
} catch (Exception e) {
System.out.println("事务回滚");
}
return invoke;
}
});
return proxy;
}
}
| service层: package test.mylo.service;
public interface IRoleService {
public void addRole();
}
package test.mylo.service.impl;
import test.mylo.service.IRoleService;
public class RoleServiceImpl implements IRoleService {
@Override
public void addRole() {
System.out.println("add Role");
}
}
package test.mylo.service;
public interface IUserService {
public void addUser();
}
package test.mylo.service.impl;
import test.mylo.service.IUserService;
public class UserServiceImpl implements IUserService {
@Override
public void addUser() {
int a = 10 / 0;
System.out.println("add User");
}
} | 测试:public class Test01 {
public static void main(String[] args) {
IRoleService role = new RoleServiceImpl();
IRoleService proxy = (IRoleService)MyFactory.getObj(role);
proxy.addRole();
}
}
结果:开启事务add Role事务提交
测试2 :开启事务事务回滚 |
|