Spring视频学习(六)JDK和cglib实现AOP
一、JDK的AOP实现--基于接口的代理模式
package cn.itcast.aop; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import cn.itcast.service.impl.PersonServiceBean; public class JDKProxyFactory implements InvocationHandler{ private Object targetObject; public Object createProxyIntance(Object targetObject){ this.targetObject = targetObject; return Proxy.newProxyInstance(this.targetObject.getClass().getClassLoader(), this.targetObject.getClass().getInterfaces(), this); } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {//环绕通知 PersonServiceBean bean = (PersonServiceBean) this.targetObject; Object result = null; if(bean.getUser()!=null){ //..... advice()-->前置通知 System.out.println("before"); try { result = method.invoke(targetObject, args); // afteradvice() -->后置通知 System.out.println("after"); } catch (RuntimeException e) { //exceptionadvice()--> 例外通知 }finally{ //finallyadvice(); -->最终通知 } }else{ System.out.println("无权调用"); } return result; } }
二、cglib的AOP实现--基于继承的代理模式
package cn.itcast.aop; import java.lang.reflect.Method; import cn.itcast.service.impl.PersonServiceBean; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; public class CGlibProxyFactory implements MethodInterceptor{ private Object targetObject; public Object createProxyIntance(Object targetObject){ this.targetObject = targetObject; Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(this.targetObject.getClass());//非final enhancer.setCallback(this); return enhancer.create(); } public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable { PersonServiceBean bean = (PersonServiceBean) this.targetObject; Object result = null; if(bean.getUser()!=null){ result = methodProxy.invoke(targetObject, args); } return result; } }
三、Junit测试
package junit.test; import org.junit.BeforeClass; import org.junit.Test; import cn.itcast.aop.CGlibProxyFactory; import cn.itcast.aop.JDKProxyFactory; import cn.itcast.service.PersonService; import cn.itcast.service.impl.PersonServiceBean; public class AOPTest { @BeforeClass public static void setUpBeforeClass() throws Exception { } @Test public void proxyTest(){ JDKProxyFactory factory = new JDKProxyFactory(); PersonService service = (PersonService) factory.createProxyIntance(new PersonServiceBean()); service.save("888"); } @Test public void proxyTest2(){ CGlibProxyFactory factory = new CGlibProxyFactory(); PersonServiceBean service = (PersonServiceBean) factory.createProxyIntance(new PersonServiceBean("xxx")); service.save("999"); } }