SPRING代理模式
1.静态代理
主题对象:Student
public interface Student { public String add(); }
目标对象:RealStudent
public class RealStudent implements Student { public String add() { System.out.println("add Ok"); return null; } }
代理对象:ProxStudent
public class ProxStudent implements Student { //对象间交互 private Student realStudent; public Student getRealStudent() { return realStudent; } public void setRealStudent(Student realStudent) { this.realStudent = realStudent; this.realStudent=realStudent; } public String add() { System.out.println("事务已经开启!"); return realStudent.add(); } }
单测
//静态代理 @Test public void test01(){ //真实主题对象 Student student=new RealStudent(); //代理对象 ProxStudent proxStudent=new ProxStudent(); proxStudent.setRealStudent(student); proxStudent.add(); }
2.JDK动态代理
接口:IUserDAO
public interface IUserDAO { public String add(); public String edit(); }
类:UserDAOImpl
public class UserDAOImpl implements IUserDAO { public String add() { System.out.println("add"); return "add"; } public String edit() { System.out.println("edit"); return "edit"; } }
单测
//JDK动态代理 @Test public void test02(){ final IUserDAO dao=new UserDAOImpl(); IUserDAO proxy=(IUserDAO) Proxy.newProxyInstance(dao.getClass().getClassLoader(), dao.getClass().getInterfaces(), new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("事务已经开启"); method.invoke(dao,args); return null; } }); //代理对象 add() edit() proxy.add(); proxy.edit(); }
3.CGLIB动态代理
public class UserService { public void dalete() { System.out.println("dalete OK"); } }
单测 方式一
//CGLIB 动态代理 一 @Test public void test03(){ final UserService service=new UserService(); Enhancer enhancer =new Enhancer(); //在内存中构建业务类的子类 enhancer.setSuperclass(service.getClass()); enhancer.setCallback(new org.springframework.cglib.proxy.InvocationHandler() { public Object invoke(Object o, Method method, Object[] objects) throws Throwable { System.out.println("事务已经开启"); method.invoke(service,objects); return null; } }); UserService proxy=(UserService)enhancer.create(); proxy.dalete(); }
单测 方式二
//CGLIB 动态代理 二 @Test public void test04(){ final UserService service=new UserService(); Enhancer enhancer =new Enhancer(); //在内存中构建业务类的子类 enhancer.setSuperclass(service.getClass()); enhancer.setCallback(new MethodInterceptor() { public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { System.out.println("事务已经开启"); methodProxy.invoke(service,objects); return null; } }); UserService proxy=(UserService)enhancer.create(); proxy.dalete(); }