Cglib动态代理Demo

cglib动态代理的主要组成
MethodInterceptor 接口的实现类
被代理的类(不用必须实现接口,但是不能是final的,final类不能被继承,所以不能被代理)
Enhancer 类设置代理关系

代码
实现MethodInterceptor接口的类

import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class CglibCallBackInvocationHandler implements MethodInterceptor {
    private Object target;

    public CglibCallBackInvocationHandler(Object target) {
        this.target = target;
    }

    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("cglib before do ....");

        Object result = method.invoke(target, objects);

        System.out.println("cglib after do ......");

        return result;
    }
}

被代理的类


public class TargetAction {
    private String info;
    public TargetAction(){

    }

    public TargetAction(String info){
        this.info=info;
    }


    public String doSomething(){
        System.out.println("cglib do proxy "+ info);

        return "proxy "+info;
    }
}


测试类

public class CglibDemo {
    public static void main(String[] args) {
        TargetAction targetAction = new TargetAction("demo1");
        CglibCallBackInvocationHandler handler = new CglibCallBackInvocationHandler(targetAction);

        Enhancer enhancer = new Enhancer();
        //设置代理什么类
        enhancer.setSuperclass(targetAction.getClass());
        //设置invoker
        enhancer.setCallback(handler);

        TargetAction result = (TargetAction) enhancer.create();

        String proxyResult = result.doSomething();

        System.out.println(proxyResult);
    }
}


jdk动态代理类请看此篇文章:

https://blog.csdn.net/goodwell__/article/details/105930337

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值