Spring AOP

#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;
    }
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值