Spring Aop的三种代理实现方式

Spring Aop的三种代理实现方式,第1张

Spring Aop的三种代理实现方式 接口:  接口实现类: 1.静态代理
public class StaticProxy implements UserDao{

    private UserDao userDao;

    //实例化静态代理的时候,将目标对象注入
    public StaticProxy(UserDao userDao){
        this.userDao = userDao;
    }

    @Override
    public int insert() {
        return userDao.insert();
    }

    @Override
    public int update() {
        System.out.println("权限验证!!!");
        return userDao.update();
    }

    @Override
    public int delete() {
        return userDao.delete();
    }

    @Override
    public void selectAll() {
        userDao.selectAll();
    }
}
测试类: 测试结果: 2.动态代理
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MyJdkProxy implements InvocationHandler {
    private UserDao userDao;

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

    //创建代理对象
    public Object createProxy(){
        Object proxy = Proxy.newProxyInstance(userDao.getClass().getClassLoader(), userDao.getClass().getInterfaces(),this);
        return  proxy;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //想要对insert方法进行增强 权限验证
        if("insert".equals(method.getName())){
            System.out.println("权限验证!!!");
            return  method.invoke(userDao,args);
        }
        return method.invoke(userDao,args);
    }
}
测试类: 测试结果: 3.CgLib代理
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 MyCglibProxy implements MethodInterceptor {
    private UserDao userDao;

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

    public Object createProxy(){
        Enhancer enhancer = new Enhancer();
        //目标对象设值父类
        enhancer.setSuperclass(userDao.getClass());
        //设值回调
        enhancer.setCallback(this);
        //生成代理
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        //对update方法进行权限验证
        if("update".equals(method.getName())){
            System.out.println("权限验证!!!");
            return  methodProxy.invokeSuper(o,objects);
        }
        return methodProxy.invokeSuper(o,objects);
    }
}
测试类: 测试结果:

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5692118.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存