JDK动态代理
package com.imooc.aop.demo1; public interface UserDao { public void save(); public void update(); public void delete(); public void find(); }
package com.imooc.aop.demo1; public class UserDaoImpl implements UserDao{ @Override public void save() { System.out.println("保存用户"); } @Override public void update() { System.out.println("修改用户"); } @Override public void delete() { System.out.println("删除用户"); } @Override public void find() { System.out.println("查询用户"); } }
package com.imooc.aop.demo1; 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 { if("save".equals(method.getName())){ System.out.println("权限校验。。。"); method.invoke(userDao,args); } return method.invoke(userDao,args); } }
package com.imooc.aop.demo1; import org.junit.Test; public class SpringDemo1 { @Test public void demo1(){ UserDao userDao=new UserDaoImpl(); UserDao proxy= (UserDao)new MyJdkProxy(userDao).createProxy(); proxy.save(); proxy.update(); proxy.delete(); proxy.find(); } }
package com.imooc.aop.demo2; public class ProductDao { public void save(){ System.out.println("保存商品..."); } public void update(){ System.out.println("更新商品..."); } public void delete(){ System.out.println("删除商品..."); } public void find(){ System.out.println("查询商品..."); } }
package com.imooc.aop.demo2; 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 ProductDao productDao; public MyCglibProxy(ProductDao productDao){ this.productDao=productDao; } public Object createProxy(){ //1.创建核心类 Enhancer enhancer=new Enhancer(); //2.设置父类 enhancer.setSuperclass(productDao.getClass()); //3.设置回调 enhancer.setCallback(this); //4.生成代理 Object proxy=enhancer.create(); return proxy; } @Override public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { if ("save".equals(method.getName())){ System.out.println("权限校验==========="); methodProxy.invokeSuper(proxy,args); } return methodProxy.invokeSuper(proxy,args); } }
package com.imooc.aop.demo2; import org.junit.Test; public class SpringDemo2 { @Test public void demo1(){ ProductDao productDao= new ProductDao(); ProductDao proxy=(ProductDao)new MyCglibProxy(productDao).createProxy(); proxy.save(); proxy.update(); proxy.delete(); proxy.find(); } }