packagecom.imooc.aop.demo1; publicinterfaceUserDao { publicvoidsave(); publicvoidupdate(); publicvoiddelete(); publicvoidfind(); }
packagecom.imooc.aop.demo1; publicclassUserDaoImplimplementsUserDao { publicvoidsave() { System.out.println("保存用户..."); } publicvoidupdate() { System.out.println("修改用户..."); } publicvoiddelete() { System.out.println("删除用户..."); } publicvoidfind() { System.out.println("查询用户..."); } }
packagecom.imooc.aop.demo1; importjava.lang.reflect.InvocationHandler; importjava.lang.reflect.Method; importjava.lang.reflect.Proxy; publicclassMyJdkProxyimplementsInvocationHandler{ privateUserDaouserDao; publicMyJdkProxy(UserDaouserDao){ this.userDao=userDao; } publicObjectcreateProxy(){ Objectproxy=Proxy.newProxyInstance(userDao.getClass().getClassLoader(),userDao.getClass().getInterfaces(),this); returnproxy; } publicObjectinvoke(Objectproxy, Methodmethod, Object[] args) throwsThrowable { if("save".equals(method.getName())){ System.out.println("权限校验..."); returnmethod.invoke(userDao,args); } returnmethod.invoke(userDao,args); } }
packagecom.imooc.aop.demo1; importorg.junit.Test; publicclassSpringDemo1 { @Testpublicvoiddemo1(){ UserDaouserDao=newUserDaoImpl(); UserDaoproxy= (UserDao)newMyJdkProxy(userDao).createProxy(); proxy.save(); proxy.update(); proxy.delete(); proxy.find(); } }
运行结果:权限校验... 保存用户... 修改用户... 删除用户... 查询用户...
packagecom.imooc.aop.demo2; publicclassProductDao { publicvoidsave(){ System.out.println("保存商品..."); } publicvoidupdate(){ System.out.println("修改商品..."); } publicvoiddelete(){ System.out.println("删除商品..."); } publicvoidfind(){ System.out.println("查询商品..."); } }
packagecom.imooc.aop.demo2; importorg.springframework.cglib.proxy.Enhancer; importorg.springframework.cglib.proxy.MethodInterceptor; importorg.springframework.cglib.proxy.MethodProxy; importjava.lang.reflect.Method; publicclassMyCglibProxyimplementsMethodInterceptor{ privateProductDaoproductDao; publicMyCglibProxy(ProductDaoproductDao){ this.productDao=productDao; } publicObjectcreateProxy(){ // 1.创建核心类Enhancerenhancer=newEnhancer(); // 2.设置父类enhancer.setSuperclass(productDao.getClass()); // 3.设置回调enhancer.setCallback(this); // 4.生成代理Objectproxy=enhancer.create(); returnproxy; } publicObjectintercept(Objectproxy, Methodmethod, Object[] args, MethodProxymethodProxy) throwsThrowable { if("save".equals(method.getName())){ System.out.println("权限校验==================="); returnmethodProxy.invokeSuper(proxy,args); } returnmethodProxy.invokeSuper(proxy,args); } }
packagecom.imooc.aop.demo2; importorg.junit.Test; publicclassSpringDemo2 { @Testpublicvoiddemo1(){ ProductDaoproductDao=newProductDao(); ProductDaoproxy= (ProductDao) newMyCglibProxy(productDao).createProxy(); proxy.save(); proxy.update(); proxy.delete(); proxy.find(); } }
运行结果:权限校验===================保存商品... 修改商品... 删除商品... 查询商品...