AOP的底层实现

Spring的AOP的底层用到了两种代理机制:

JDK动态代理:

针对实现了接口的类产生代理

Cglib动态代理:

针对没有实现接口的类产生的代理,应用的是底层的字节码增强技术,生成当前类的子类对象

JDK动态代理增强一个类中的方法

public class MyJDKProxy implements InvocationHandler{

private UserDao userDao;

public MyJDKProxy(UserDao userDao) {
this.userDao = userDao;
}

public UserDao createProxy(){
UserDao userDaoProxy = (UserDao) Proxy.newProxyInstance(userDao.getClass().getClassLoader(),userDao.getClass().getInterfaces(),this);
return userDaoProxy;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if("save".equals(method.getName())){
System.out.println("权限校验");
}
return method.invoke(userDao,args);
}
}

Cglib动态代理增强一个类中的方法

public class MyCgLibProxy implements MethodInterceptor{
private CustomerDao mCustomerDao;

public MyCgLibProxy(CustomerDao customerDao) {
mCustomerDao = customerDao;
}

//生成代理方法:
public CustomerDao createProxy(){
//创建Cglib的核心类
Enhancer enhancer = new Enhancer();
//设置父类
enhancer.setSuperClass(CustomerDao.class);
//设置回调
enhancer.setCallback(this);
//生成代理
CustomerDao customerDaoProxy = (CustomerDao)enhancer.create();
return customerDaoProxy;
}

@Override
public Object intercept(Object proxy,Method method,Object[] args,MethodProxy methodProxy) throws Throwable{
if("delete".equals(method.getName())){
Object obj = methodProxy.invokeSuper(proxy,args);
System.out.println("日志记录====");
return obj;
}
return methodProxy.invokeSuper(proxy,args);
}
}