cglib代理的原理是通过继承实现对目标对象的代理
//1.接口 package cn.itcast.service; public interface UserService { void save(); void delete(); void update(); void find(); }
// 接口的实现类 -->被代理的对象 package cn.itcast.service; public class UserServiceImpl implements UserService { @Override public void save() { System.out.println("保存用户!"); //int i = 1/0; } @Override public void delete() { System.out.println("删除用户!"); } @Override public void update() { System.out.println("更新用户!"); } @Override public void find() { System.out.println("查找用户!"); } }
//3.实现cglib代理 package cn.itcast.c_proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import org.springframework.cglib.proxy.Callback; import org.springframework.cglib.proxy.Enhancer; import org.springframework.cglib.proxy.MethodInterceptor; import org.springframework.cglib.proxy.MethodProxy; import cn.itcast.service.UserService; import cn.itcast.service.UserServiceImpl; //观光代码=>cglib代理 public class UserServiceProxyFactory2 implements MethodInterceptor { public UserService getUserServiceProxy(){ Enhancer en = new Enhancer();//帮我们生成代理对象 en.setSuperclass(UserServiceImpl.class);//设置对谁进行代理 en.setCallback(this);//代理要做什么 UserService us = (UserService) en.create();//创建代理对象 return us; } @Override public Object intercept(Object prxoyobj, Method method, Object[] arg, MethodProxy methodProxy) throws Throwable { //打开事务 System.out.println("打开事务!"); //调用原有方法 Object returnValue = methodProxy.invokeSuper(prxoyobj, arg); //提交事务 System.out.println("提交事务!"); return returnValue; } }
//4.测试文件 package cn.itcast.c_proxy; import org.junit.Test; import cn.itcast.service.UserService; import cn.itcast.service.UserServiceImpl; public class Demo { @Test //动态代理 public void fun1(){ UserService us = new UserServiceImpl(); UserServiceProxyFactory factory = new UserServiceProxyFactory(us); UserService usProxy = factory.getUserServiceProxy(); usProxy.save(); //代理对象与被代理对象实现了相同的接口 //代理对象 与 被代理对象没有继承关系 System.out.println(usProxy instanceof UserServiceImpl );//false } @Test public void fun2(){ UserServiceProxyFactory2 factory = new UserServiceProxyFactory2(); UserService usProxy = factory.getUserServiceProxy(); usProxy.save(); //判断代理对象是否属于被代理对象类型 //代理对象继承了被代理对象=>true System.out.println(usProxy instanceof UserServiceImpl );//true } }