java 动态代理

本文介绍了Spring框架中AOP的实现原理,重点探讨了Java动态代理机制,包括JDK动态代理与CGLIB动态代理两种方式。通过具体示例展示了如何创建代理类并调用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.动态代理

    Spring的两个核心是Ioc和Aop,依赖注入就不多说了,对于Aop,我们不仅需要知道怎么使用,还需要知道原理,具体是怎么实现的;Aop的原理就是java的动态代理机制;另外rpc的远程调用也是通过动态代理技术;动态代理怎么理解那?通俗的理解动态代理,可以类比明星的经纪人,通常对外接触的都是明星的经纪人,比如接电影和一些商业活动;然后执行的时候才是明星本人;明星经纪人代理了明星的活动,可以做一些其他的事情比如签合同啊之类的,然后再去让明星去执行;代理类也是一样,真正执行的行为还是真实的类去执行的,只不过代理类在这之前或者之后可以做一些其他的行为,看起来就像是代理类具有了真正类的行为一样;文章会通过两个demo来分别演示这两种方式具体是如何来做的,最后总结下两种方式各自的优缺点;

    Spring中,实现动态代理有两种方式,分别是jdk动态代理和CGLIB动态代理技术;下面分别介绍下这两种方式;首先是jdk动态代理,jdk的动态代理机制中,主要有两个重要的类和接口,分别是InvocationHandler(Interface)和Proxy(Class);

2.JDK动态代理实例

首先通过一个实例演示下怎么创建代理类,如何调用;

    1>首先定义一个接口类;

package com.example.springbootDemo.service.DynamicProxy;

public interface Subject {

    public void rent();

    public void hello(String str);
}

2>然后定义一个类来实现它

package com.example.springbootDemo.service.DynamicProxy;

public class RealSubject implements Subject {
    @Override
    public void rent() {
        System.out.println("I want to rent my house");
    }

    @Override
    public void hello(String str) {
        System.out.println("hello: " + str);
    }
}

3>我们要创建一个代理类,代理类必须实现InvocationHandler 这个接口

package com.example.springbootDemo.service.DynamicProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class DynamicProxy implements InvocationHandler {
    // 这个就是我们要代理的真实对象
    private Object subject;

    public DynamicProxy(Object subject) {
        this.subject = subject;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //  在代理真实对象前我们可以添加一些自己的操作
        System.out.println("before rent house");

        System.out.println("Method:" + method);

        //    当代理对象调用真实对象的方法时,其会自动的跳转到代理对象关联的handler对象的invoke方法来进行调用
        method.invoke(subject, args);

        //  在代理真实对象后我们也可以添加一些自己的操作
        System.out.println("after rent house");
        return null;
    }
}

4>最后一个main方法来进行调用测试

package com.example.springbootDemo.service.DynamicProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

public class Client {
    public static void main(String[] args) {
        //    我们要代理的真实对象
        Subject realSubject = new RealSubject();

        //    我们要代理哪个真实对象,就将该对象传进去,最后是通过该真实对象来调用其方法的
        InvocationHandler handler = new DynamicProxy(realSubject);

         /*
         * 通过Proxy的newProxyInstance方法来创建我们的代理对象,我们来看看其三个参数
         * 第一个参数 handler.getClass().getClassLoader() ,我们这里使用handler这个类的ClassLoader对象来加载我们的代理对象
         * 第二个参数realSubject.getClass().getInterfaces(),我们这里为代理对象提供的接口是真实对象所实行的接口,表示我要代理的是该真实对象,这样我就能调用这组接口中的方法了
         * 第三个参数handler, 我们这里将这个代理对象关联到了上方的 InvocationHandler 这个对象上
         */
        Subject subject = (Subject) Proxy.newProxyInstance(handler.getClass().getClassLoader(), realSubject
                .getClass().getInterfaces(), handler);

        System.out.println(subject.getClass().getName());
        subject.rent();
        subject.hello("world");

    }
}

返回结果

com.sun.proxy.$Proxy0
before rent house
Method:public abstract void com.example.springbootDemo.service.DynamicProxy.Subject.rent()
I want to rent my house
after rent house
before rent house
Method:public abstract void com.example.springbootDemo.service.DynamicProxy.Subject.hello(java.lang.String)
hello: world
after rent house
3.分析

先看下InvocationHandler的invoke接口定义

/**
     * Processes a method invocation on a proxy instance and returns
     * the result.  This method will be invoked on an invocation handler
     * when a method is invoked on a proxy instance that it is
     * associated with.
     *
     * @param   proxy the proxy instance that the method was invoked on
     *
     * @param   method the {@code Method} instance corresponding to
     * the interface method invoked on the proxy instance.  The declaring
     * class of the {@code Method} object will be the interface that
     * the method was declared in, which may be a superinterface of the
     * proxy interface that the proxy class inherits the method through.
     *
     * @param   args an array of objects containing the values of the
     * arguments passed in the method invocation on the proxy instance,
     * or {@code null} if interface method takes no arguments.
     * Arguments of primitive types are wrapped in instances of the
     * appropriate primitive wrapper class, such as
     * {@code java.lang.Integer} or {@code java.lang.Boolean}.
public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable;

简单做个说明:

1>proxy 参数代表方法运行的代理的实例;指代代理的真实对象;

2>method 指代我们调用的真实对象的某个方法Mehtod;

3>args 指代调用真实对象的某个方法的参数;

再看下Proxy.newProxyInstance方法

public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)

这个方法的作用就是返回一个动态代理对象,接受三个参数:

ClassLoader loader:一个ClassLoader对象,定义了由哪个ClassLoader对象来对生成的代理对象进行加载;

interfaces:一个interface数组,表示的需要代理的对象提供一组什么样的接口,如果提供了一组接口给它,那么之后就可以调用代理类的这些方法了

h:一个InvocationHandler对象,表示的是当我这个动态代理对象在调用方法的时候,会关联到哪一个InvocationHandler对象上

4.cglib动态代理

    cglib可以在运行期间动态生成Java类,用Cglib生成的代理类是目标类的子类,并且不需要目标类实现某个接口,这个是跟jdk动态代理最大的不同之处,拦截器中intercept方法中内容正好是代理类中的方法体;

还是通过上面的例子来做演示:

    private Object targetObject;

    public CglibProxy(Object targetObject) {
        this.targetObject = targetObject;
    }

    public Object createProxyInstance(){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(this.targetObject.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

        System.out.println("before rent house");

        System.out.println("Method:" + method);
        Object returnValue = methodProxy.invoke(this.targetObject, objects);

        System.out.println("after rent house");
        return returnValue;
    }

    public static void main(String[] args) {
        RealSubject realSubject = new RealSubject();
        CglibProxy cglibProxy = new CglibProxy(realSubject);
        RealSubject proxyInstance = (RealSubject) cglibProxy.createProxyInstance();
        proxyInstance.hello("aaaa");
    }


5.总结

   Spring两种代理方式分别是jdk动态代理和cglib动态代理

1.若目标对象实现了若干接口,使用jdk的java.lang.reflect.Proxy类代理;优点是因为存在接口,所以从耦合;缺点:为每个类创建一个接口;

2.若目标对象没有实现任何接口,使用cglib库实现生成目标类的子类;优点因为目标类和代理类是继承的关系,所以不需要有接口的存在;缺点:因为没使用接口,所以系统的耦合性没有jdk动态代理好一些;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值