public class StaticProxy implements UserDao{ private UserDao userDao; //实例化静态代理的时候,将目标对象注入 public StaticProxy(UserDao userDao){ this.userDao = userDao; } @Override public int insert() { return userDao.insert(); } @Override public int update() { System.out.println("权限验证!!!"); return userDao.update(); } @Override public int delete() { return userDao.delete(); } @Override public void selectAll() { userDao.selectAll(); } }测试类: 测试结果: 2.动态代理
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class MyJdkProxy implements InvocationHandler { private UserDao userDao; public MyJdkProxy(UserDao userDao){ this.userDao = userDao; } //创建代理对象 public Object createProxy(){ Object proxy = Proxy.newProxyInstance(userDao.getClass().getClassLoader(), userDao.getClass().getInterfaces(),this); return proxy; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //想要对insert方法进行增强 权限验证 if("insert".equals(method.getName())){ System.out.println("权限验证!!!"); return method.invoke(userDao,args); } return method.invoke(userDao,args); } }测试类: 测试结果: 3.CgLib代理
import org.springframework.cglib.proxy.Enhancer; import org.springframework.cglib.proxy.MethodInterceptor; import org.springframework.cglib.proxy.MethodProxy; import java.lang.reflect.Method; public class MyCglibProxy implements MethodInterceptor { private UserDao userDao; public MyCglibProxy(UserDao userDao){ this.userDao = userDao; } public Object createProxy(){ Enhancer enhancer = new Enhancer(); //目标对象设值父类 enhancer.setSuperclass(userDao.getClass()); //设值回调 enhancer.setCallback(this); //生成代理 return enhancer.create(); } @Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { //对update方法进行权限验证 if("update".equals(method.getName())){ System.out.println("权限验证!!!"); return methodProxy.invokeSuper(o,objects); } return methodProxy.invokeSuper(o,objects); } }测试类: 测试结果:
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)