Cglib代理实现

Cglib代理

JDK的动态代理机制只能代理实现了接口的类,而不能实现接口的类就不能实现JDK的动态代理,cglib是针对类来实现代理的,他的原理是对指定的目标类生成一个子类,并覆盖其中方法实现增强,但因为采用的是继承,所以不能对final修饰的类进行代理。
闲话少说,直接上代码
被代理的类RealSubject 注意,这里的RealSubject和JDK动态代理的RealSubject有一定的区别,它没有实现Subject接口,就是一个简单类

RealSubject被代理类

@Component
public class RealSubject
{
    public void excute()
    {
        System.out.println("this is real implements method");
    }

    public void hello()
    {
        System.out.println("this is real implements say hello");
    }
}

Cglib代理类

 /**
     *@DESCRIPTION :o生成的代理对象,method:被代理对象方法,objects:方法入参,methodProxy:代理方法
     *@AUTHOR SongHongWei
     *@TIME   2018/8/11-15:35
     *@CLASS_NAME CglibProxy
    **/ 
 public class CglibProxy implements MethodInterceptor
{
    @Override
    public Object intercept(Object o, Method method, Object[] objects,
        MethodProxy methodProxy)
        throws Throwable
    {
        System.out.println("cglib proxy doing someting before...");
        Object invoke = null;
        try
        {   //代理类调用父类的方法
            invoke = methodProxy.invokeSuper(o, objects);
            System.out.println("output proxy return value..." + invoke);
        }
        catch (Exception e)
        {
            System.out.println("catch exception ...");
            throw e;
        }
        finally
        {
            System.out.println("cglib proxy doing something after...");
        }
        return invoke;
    }
}

客户端

public class Client
{
    public static void main(String[] args)
    {
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");//作用是生成代理后的class文件
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(RealSubject.class);//实际执行的对象
        enhancer.setCallback(new CglibProxy());//代理者
        RealSubject subject = (RealSubject)enhancer.create();//代理对象
        subject.excute();
        subject.hello();

    }
}

猜你喜欢

转载自blog.csdn.net/u010859650/article/details/81587230