Jave利用动态代理实现AOP

来源:互联网 发布:开启php的curl扩展 编辑:程序博客网 时间:2024/06/05 01:54

1.JDK Proxy模拟AOP代理对象实例:


package com.skymr.spring.test.aopimpl;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;/** * JDK的代理技术 * @author skymr * */public class JDKProxyFactory implements InvocationHandler{//目标对象,要代理的对象private Object targetObject;/** * 生成代理对象 * @param targetObject * @return */public Object createProxyObject(Object targetObject){this.targetObject = targetObject;//第一个参数:ClassLoader//第二个参数:Interface接口数组,目标对象的接口传入后,代理对象会实现接口//第三个参数:回调参数return Proxy.newProxyInstance(this.getClass().getClassLoader(), targetObject.getClass().getInterfaces(), this);}public Object invoke(Object proxy, Method method, Object[] args)throws Throwable {//可进行限拦截,日志记录等return method.invoke(targetObject, args);}}
测试:

@org.junit.Testpublic void ownAopTest(){UserInfoDao dao = (UserInfoDao)new JDKProxyFactory().createProxyObject(new UserInfoDaoBean());dao.update();}

2.CGLIB模拟AOP:

package com.skymr.spring.test.aopimpl;import java.lang.reflect.Method;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 target;public Object createProxyInstance(Object target){this.target = target;Enhancer enhancer = new Enhancer();enhancer.setSuperclass(target.getClass());enhancer.setCallback(this);return enhancer.create();}public Object intercept(Object proxyObject, Method method, Object[] args,MethodProxy methodProxy) throws Throwable {return methodProxy.invoke(target, args);}}

测试

@org.junit.Testpublic void ownAopTest2(){UserInfoDao dao = (UserInfoDao)new CGlibProxyFactory().createProxyInstance(new UserInfoDaoBean());dao.update();}

cglib方式相比jdk proxy方式而言,它可以不用接口



0 0
原创粉丝点击