#JDK动态代理类
package com.hxx.utils.proxy;
import com.hxx.aop.UserDao;
import com.hxx.utils.aspect.MyAspect;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* JDK代理类
*/
public class MyProxy implements InvocationHandler {
private UserDao userDao;
public Object createProxy(UserDao userDao){
this.userDao=userDao;
ClassLoader classLoader=MyProxy.class.getClassLoader();
Class[] classes=userDao.getClass().getInterfaces();
return Proxy.newProxyInstance(classLoader,classes,this);
}
/*
*所有动态代理类的方法调用,都会交由invoke()方法去处理
* proxy被代理的对象
* method将要被执行的方法信息(反射)
* args执行方法时需要的参数
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//创建切面类对象
MyAspect myAspect=new MyAspect();
//前增强
myAspect.check_Permission();
//在目标类上调用方法,并传入参数
Object obj=method.invoke(userDao,args);
myAspect.log();
return obj;
}
}
#CGLib动态代理
package com.hxx.utils.proxy;
import com.hxx.utils.aspect.MyAspect;
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 CglibProxy implements MethodInterceptor {
//代理方法
public Object createProxy(Object target){
//创建一个动态对象
Enhancer enhancer=new Enhancer();
//确定需要增强的类,设置其父类
enhancer.setSuperclass(target.getClass());
//添加回调函数
enhancer.setCallback(this);
//返回创建的代理类
return enhancer.create();
}
/**
*proxy CGlib根据指定父类生成的代理对象
* method拦截的方法
* methodProxy方法的代理对象,用于执行父类的方法
*/
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
//创建切面类对象
MyAspect myAspect=new MyAspect();
//前增强
myAspect.check_Permission();
//目标方法执行
Object obj=methodProxy.invokeSuper(o,objects);
//后增强
myAspect.log();
return obj;
}
}