cglib动态代理和jdk动态代理的区别与应用

来自:https://blog.csdn.net/doujinlong1/article/details/80680149

1,引入

如果从一个Controller调用Service的非事务方法a,然后在a里调用事务方法b,b事务生效吗?

 public void update() {
        updateActual();
        int a = 1 / 0;
    }
    @Transactional
    public void updateActual() {
        WithHoldInfoVO vo = new WithHoldInfoVO();
        vo.setId(18);
        vo.setStatus(5);
        withholdMapper.updateWithHoldInfo(vo);
        WithHoldInfoVO vo1 = new WithHoldInfoVO();
        vo1.setId(27);
        vo1.setStatus(5);
        withholdMapper.updateWithHoldInfo(vo1);
    }

形如这样,如果从Controller层直接调用update方法,updateActual方法的事务可以生效吗?如果不能,那么如何才能使事务生效?


2,什么是代理?

代理,简单来说,就是代替处理,代替原有操作者去处理一件事。在Java中一般是2种,静态代理和动态代理,动态代理又分为CGLIB和jdk自带。

 

3,如何使用?

3.1静态代理:

public class StaticProxy {
    public static void main(String[] args) {
        Singer singer = new Agent(new Star());
        singer.sing();
    }
}
/**
* 代理实现,代理了歌星,唱歌的时候 会先在歌手唱歌之前收钱,然后再唱歌
*/
class Agent implements Singer {
    Star s;
    public Agent(Star s) {
        super();
        this.s = s;
    }
    @Override
    public void sing() {
        System.out.println("在歌手唱歌之前收钱....");
        s.sing();
    }
}
/**
* 真实实现,一个歌星
*/
class Star implements Singer {
    @Override
    public void sing() {
        System.out.println("Star Singing~~~");
    }
}
/**
* 最顶层接口 歌手
*/
interface Singer {
    void sing();
}

3.2 jdk动态代理

 

@SuppressWarnings("restriction")
public class JavaProxyTest {
    public static void main(String[] args) throws Exception {
        JavaProxyInterface javaProxyInterface = new ConcreteClass();
        
        JavaProxyInterface newJavaProxyInterface = (JavaProxyInterface) Proxy.newProxyInstance(
                JavaProxyTest.class.getClassLoader(), new Class[] { JavaProxyInterface.class },
                new MyInvocationHandler(javaProxyInterface));
        //这里可以看到这个类以及被代理,在执行方法前会执行aopMethod()。这里需要注意的是oneDay()方法和oneDayFinal()的区别。oneDayFinal的方法aopMethod执行1次,oneDay的aopMethod执行1次
        newJavaProxyInterface.gotoSchool();
        newJavaProxyInterface.gotoWork();
        newJavaProxyInterface.oneDayFinal();
        newJavaProxyInterface.oneDay();
    }
}
/**
* InvocationHandler 的一个实现,实际上处理代理的逻辑在这里
*/
class MyInvocationHandler implements InvocationHandler {
    JavaProxyInterface javaProxy;
    public MyInvocationHandler(JavaProxyInterface javaProxy) {
        this.javaProxy = javaProxy;
    }
    private void aopMethod() {
        System.out.println("before method");
    }
	//继承方法,代理时实际执行的犯法,如果要实现原方法,则需要调用method.invoke(javaProxy, args),这里还调用了一个aopMethod(),可以类比于Spring中的切面before注解。
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        aopMethod();
        return method.invoke(javaProxy, args);
    }
}
/**
* 需要一个最顶层接口,必须
*/
interface JavaProxyInterface {
    void gotoSchool();
    void gotoWork();
    void oneDay();
    void oneDayFinal();
}
/**
* 需要被代理的类,实现了顶层接口,非必须
*/
class ConcreteClass implements JavaProxyInterface {
    @Override
    public void gotoSchool() {
        System.out.println("gotoSchool");
    }
    @Override
    public void gotoWork() {
        System.out.println("gotoWork");
    }
    @Override
    public void oneDay() {
        gotoSchool();
        gotoWork();
    }
    @Override
    public final void oneDayFinal() {
        gotoSchool();
        gotoWork();
    }
}

3.3 cglib 动态代理

 
public class CglibProxyTest {
    public static void main(String[] args) throws Exception {
        CglibTestSon CglibTestSon = new CglibTestSon();
        Enhancer enhancer = new Enhancer();
        Callback s = new MthdInvoker(CglibTestSon);
        enhancer.setSuperclass(CglibTestSon.class);
        Callback callbacks[] = new Callback[] { s };
        enhancer.setCallbacks(callbacks);
        CglibTestSon CglibTestSon2 = (CglibTestSon) enhancer.create();
        CglibTestSon2.gotoHome();
        CglibTestSon2.gotoSchool();
		////这里可以看到这个类以及被代理,在执行方法前会执行aopMethod()。这里需要注意的是oneDay()方法和onedayFinal()的区别。onedayFinal的方法aopMethod执行2次,oneDay的aopMethod执行1次 ,注意这里和jdk的代理的区别
        CglibTestSon2.oneday();
        CglibTestSon2.onedayFinal();
    }
}
/**
* 需要被代理的类,不需要实现顶层接口
*/
class CglibTestSon {
    public CglibTestSon() {
    }
    public void gotoHome() {
        System.out.println("============gotoHome============");
    }
    public void gotoSchool() {
        System.out.println("===========gotoSchool============");
    }
    public void oneday() {
        gotoHome();
        gotoSchool();
    }
    public final void onedayFinal() {
        gotoHome();
        gotoSchool();
    }
}
/**
* 可以类比于jdk动态代理中的InvocationHandler ,实际上被代理后重要的类,实际上后续执行的就是intercept里的方法,如果需要执行原来的方法,则调用 method.invoke(s, args);这里也加了一个aopMethod();
*/
class MthdInvoker implements MethodInterceptor {
    private CglibTestSon s;
    public MthdInvoker(CglibTestSon s) {
        this.s = s;
    }
    private void aopMethod() {
        System.out.println("i am aopMethod");
    }
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        aopMethod();
        Object a = method.invoke(s, args);
        return a;
    }
}
 
cglib 需要的maven配置:

		
			cglib
			cglib
			3.2.6
		

    

4,区别

名称 备注
静态代理 简单,代理模式,是动态代理的理论基础。常见使用在代理模式
jdk动态代理

需要有顶层接口才能使用,但是在只有顶层接口的时候也可以使用,常见是mybatis的mapper文件是代理。

使用反射完成。使用了动态生成字节码技术。

cglib动态代理 可以直接代理类,使用字节码技术,不能对 final类进行继承。使用了动态生成字节码技术。

5,底层怎么实现呢?

都知道是动态代理是使用动态生成字节码技术生成了字节码,那么生成的字节码有什么区别呢?怎么看生成的字节码呢?如何生成的字节码呢?

5.1 jdk底层实现

字节码最后是靠这一句来生成,

byte[] proxyClassFile = ProxyGenerator.generateProxyClass(proxyName, interfaces); // proxyName 为类名,interfaces为顶层接口Class
//如果需要看,可以将字节码写入文件进行观察
File file = new File("D:/testProxy/Ddd.class");
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(bs);
fileOutputStream.flush();
fileOutputStream.close();

自己观察可以从Proxy.newProxyInstance( ClassLoader paramClassLoader,  Class[] paramArrayOfClass,  InvocationHandler paramInvocationHandler)进行观察,简单来看就是先生成新的class文件,然后加载到jvm中,然后使用反射,先用class取得他的构造方法,然后使用构造方法反射得到他的一个实例。

标红的是最复杂的。然后cglib的实现原理基本一致,唯一的区别在于生成新的class文件方式和结果不一样。

5.2 cglib 底层实现

直接上最终生成字节码的代码。需要注意的是这里要想执行这句话,必须在实现cglib动态代理的代码之后,否则取不到DefaultGeneratorStrategy的实例。

byte[] bs = DefaultGeneratorStrategy.INSTANCE.generate(enhancer);
FileOutputStream fileOutputStream = new FileOutputStream("D:/testProxy/Cc.class");
fileOutputStream.write(bs);
fileOutputStream.flush();
fileOutputStream.close();

跟踪enhancer.create(); 这个代码可以看具体怎么生成字节码,怎么将字节码转化为类。过程基本雷同于jdk,主要区别在于生成字节码的区别。

5.3 小结

这里生成代码的过程中,都使用了缓存,jdk自带的使用了weakReference引用,而cglib使用的直接是 WeakHashMap,基本也类似。

6,生成的字节码到底是什么样子的呢?

6.1 cglib

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package aaa;

import java.lang.reflect.Method;
import net.sf.cglib.core.ReflectUtils;
import net.sf.cglib.core.Signature;
import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Factory;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class CglibTestSon$$EnhancerByCGLIB$$3119e01d extends CglibTestSon implements Factory {
    private boolean CGLIB$BOUND;
    public static Object CGLIB$FACTORY_DATA;
    private static final ThreadLocal CGLIB$THREAD_CALLBACKS;
    private static final Callback[] CGLIB$STATIC_CALLBACKS;
    private MethodInterceptor CGLIB$CALLBACK_0;
    private static Object CGLIB$CALLBACK_FILTER;
    private static final Method CGLIB$gotoHome$0$Method;
    private static final MethodProxy CGLIB$gotoHome$0$Proxy;
    private static final Object[] CGLIB$emptyArgs;
    private static final Method CGLIB$gotoSchool$1$Method;
    private static final MethodProxy CGLIB$gotoSchool$1$Proxy;
    private static final Method CGLIB$oneday$2$Method;
    private static final MethodProxy CGLIB$oneday$2$Proxy;
    private static final Method CGLIB$equals$3$Method;
    private static final MethodProxy CGLIB$equals$3$Proxy;
    private static final Method CGLIB$toString$4$Method;
    private static final MethodProxy CGLIB$toString$4$Proxy;
    private static final Method CGLIB$hashCode$5$Method;
    private static final MethodProxy CGLIB$hashCode$5$Proxy;
    private static final Method CGLIB$clone$6$Method;
    private static final MethodProxy CGLIB$clone$6$Proxy;

    static void CGLIB$STATICHOOK2() {
        CGLIB$THREAD_CALLBACKS = new ThreadLocal();
        CGLIB$emptyArgs = new Object[0];
        Class var0 = Class.forName("com.rrc.finance.CglibTestSon$$EnhancerByCGLIB$$3119e01d");
        Class var1;
        Method[] var10000 = ReflectUtils.findMethods(new String[]{"equals", "(Ljava/lang/Object;)Z", "toString", "()Ljava/lang/String;", "hashCode", "()I", "clone", "()Ljava/lang/Object;"}, (var1 = Class.forName("java.lang.Object")).getDeclaredMethods());
        CGLIB$equals$3$Method = var10000[0];
        CGLIB$equals$3$Proxy = MethodProxy.create(var1, var0, "(Ljava/lang/Object;)Z", "equals", "CGLIB$equals$3");
        CGLIB$toString$4$Method = var10000[1];
        CGLIB$toString$4$Proxy = MethodProxy.create(var1, var0, "()Ljava/lang/String;", "toString", "CGLIB$toString$4");
        CGLIB$hashCode$5$Method = var10000[2];
        CGLIB$hashCode$5$Proxy = MethodProxy.create(var1, var0, "()I", "hashCode", "CGLIB$hashCode$5");
        CGLIB$clone$6$Method = var10000[3];
        CGLIB$clone$6$Proxy = MethodProxy.create(var1, var0, "()Ljava/lang/Object;", "clone", "CGLIB$clone$6");
        var10000 = ReflectUtils.findMethods(new String[]{"gotoHome", "()V", "gotoSchool", "()V", "oneday", "()V"}, (var1 = Class.forName("com.rrc.finance.CglibTestSon")).getDeclaredMethods());
        CGLIB$gotoHome$0$Method = var10000[0];
        CGLIB$gotoHome$0$Proxy = MethodProxy.create(var1, var0, "()V", "gotoHome", "CGLIB$gotoHome$0");
        CGLIB$gotoSchool$1$Method = var10000[1];
        CGLIB$gotoSchool$1$Proxy = MethodProxy.create(var1, var0, "()V", "gotoSchool", "CGLIB$gotoSchool$1");
        CGLIB$oneday$2$Method = var10000[2];
        CGLIB$oneday$2$Proxy = MethodProxy.create(var1, var0, "()V", "oneday", "CGLIB$oneday$2");
    }

    final void CGLIB$gotoHome$0() {
        super.gotoHome();
    }

    public final void gotoHome() {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (this.CGLIB$CALLBACK_0 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }

        if (var10000 != null) {
            var10000.intercept(this, CGLIB$gotoHome$0$Method, CGLIB$emptyArgs, CGLIB$gotoHome$0$Proxy);
        } else {
            super.gotoHome();
        }
    }

    final void CGLIB$gotoSchool$1() {
        super.gotoSchool();
    }

    public final void gotoSchool() {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (this.CGLIB$CALLBACK_0 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }

        if (var10000 != null) {
            var10000.intercept(this, CGLIB$gotoSchool$1$Method, CGLIB$emptyArgs, CGLIB$gotoSchool$1$Proxy);
        } else {
            super.gotoSchool();
        }
    }

    final void CGLIB$oneday$2() {
        super.oneday();
    }

    public final void oneday() {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (this.CGLIB$CALLBACK_0 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }

        if (var10000 != null) {
            var10000.intercept(this, CGLIB$oneday$2$Method, CGLIB$emptyArgs, CGLIB$oneday$2$Proxy);
        } else {
            super.oneday();
        }
    }

    final boolean CGLIB$equals$3(Object var1) {
        return super.equals(var1);
    }

    public final boolean equals(Object var1) {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (this.CGLIB$CALLBACK_0 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }

        if (var10000 != null) {
            Object var2 = var10000.intercept(this, CGLIB$equals$3$Method, new Object[]{var1}, CGLIB$equals$3$Proxy);
            return var2 == null ? false : (Boolean)var2;
        } else {
            return super.equals(var1);
        }
    }

    final String CGLIB$toString$4() {
        return super.toString();
    }

    public final String toString() {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (this.CGLIB$CALLBACK_0 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }

        return var10000 != null ? (String)var10000.intercept(this, CGLIB$toString$4$Method, CGLIB$emptyArgs, CGLIB$toString$4$Proxy) : super.toString();
    }

    final int CGLIB$hashCode$5() {
        return super.hashCode();
    }

    public final int hashCode() {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (this.CGLIB$CALLBACK_0 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }

        if (var10000 != null) {
            Object var1 = var10000.intercept(this, CGLIB$hashCode$5$Method, CGLIB$emptyArgs, CGLIB$hashCode$5$Proxy);
            return var1 == null ? 0 : ((Number)var1).intValue();
        } else {
            return super.hashCode();
        }
    }

    final Object CGLIB$clone$6() throws CloneNotSupportedException {
        return super.clone();
    }

    protected final Object clone() throws CloneNotSupportedException {
        MethodInterceptor var10000 = this.CGLIB$CALLBACK_0;
        if (this.CGLIB$CALLBACK_0 == null) {
            CGLIB$BIND_CALLBACKS(this);
            var10000 = this.CGLIB$CALLBACK_0;
        }

        return var10000 != null ? var10000.intercept(this, CGLIB$clone$6$Method, CGLIB$emptyArgs, CGLIB$clone$6$Proxy) : super.clone();
    }

    public static MethodProxy CGLIB$findMethodProxy(Signature var0) {
        String var10000 = var0.toString();
        switch(var10000.hashCode()) {
        case -1311123629:
            if (var10000.equals("gotoHome()V")) {
                return CGLIB$gotoHome$0$Proxy;
            }
            break;
        case -508378822:
            if (var10000.equals("clone()Ljava/lang/Object;")) {
                return CGLIB$clone$6$Proxy;
            }
            break;
        case 800823646:
            if (var10000.equals("gotoSchool()V")) {
                return CGLIB$gotoSchool$1$Proxy;
            }
            break;
        case 1826985398:
            if (var10000.equals("equals(Ljava/lang/Object;)Z")) {
                return CGLIB$equals$3$Proxy;
            }
            break;
        case 1913648695:
            if (var10000.equals("toString()Ljava/lang/String;")) {
                return CGLIB$toString$4$Proxy;
            }
            break;
        case 1984935277:
            if (var10000.equals("hashCode()I")) {
                return CGLIB$hashCode$5$Proxy;
            }
            break;
        case 2071325759:
            if (var10000.equals("oneday()V")) {
                return CGLIB$oneday$2$Proxy;
            }
        }

        return null;
    }

    public CglibTestSon$$EnhancerByCGLIB$$3119e01d() {
        CGLIB$BIND_CALLBACKS(this);
    }

    public static void CGLIB$SET_THREAD_CALLBACKS(Callback[] var0) {
        CGLIB$THREAD_CALLBACKS.set(var0);
    }

    public static void CGLIB$SET_STATIC_CALLBACKS(Callback[] var0) {
        CGLIB$STATIC_CALLBACKS = var0;
    }

    private static final void CGLIB$BIND_CALLBACKS(Object var0) {
        CglibTestSon$$EnhancerByCGLIB$$3119e01d var1 = (CglibTestSon$$EnhancerByCGLIB$$3119e01d)var0;
        if (!var1.CGLIB$BOUND) {
            var1.CGLIB$BOUND = true;
            Object var10000 = CGLIB$THREAD_CALLBACKS.get();
            if (var10000 == null) {
                var10000 = CGLIB$STATIC_CALLBACKS;
                if (CGLIB$STATIC_CALLBACKS == null) {
                    return;
                }
            }

            var1.CGLIB$CALLBACK_0 = (MethodInterceptor)((Callback[])var10000)[0];
        }

    }

    public Object newInstance(Callback[] var1) {
        CGLIB$SET_THREAD_CALLBACKS(var1);
        CglibTestSon$$EnhancerByCGLIB$$3119e01d var10000 = new CglibTestSon$$EnhancerByCGLIB$$3119e01d();
        CGLIB$SET_THREAD_CALLBACKS((Callback[])null);
        return var10000;
    }

    public Object newInstance(Callback var1) {
        CGLIB$SET_THREAD_CALLBACKS(new Callback[]{var1});
        CglibTestSon$$EnhancerByCGLIB$$3119e01d var10000 = new CglibTestSon$$EnhancerByCGLIB$$3119e01d();
        CGLIB$SET_THREAD_CALLBACKS((Callback[])null);
        return var10000;
    }

    public Object newInstance(Class[] var1, Object[] var2, Callback[] var3) {
        CGLIB$SET_THREAD_CALLBACKS(var3);
        CglibTestSon$$EnhancerByCGLIB$$3119e01d var10000 = new CglibTestSon$$EnhancerByCGLIB$$3119e01d;
        switch(var1.length) {
        case 0:
            var10000.();
            CGLIB$SET_THREAD_CALLBACKS((Callback[])null);
            return var10000;
        default:
            throw new IllegalArgumentException("Constructor not found");
        }
    }

    public Callback getCallback(int var1) {
        CGLIB$BIND_CALLBACKS(this);
        MethodInterceptor var10000;
        switch(var1) {
        case 0:
            var10000 = this.CGLIB$CALLBACK_0;
            break;
        default:
            var10000 = null;
        }

        return var10000;
    }

    public void setCallback(int var1, Callback var2) {
        switch(var1) {
        case 0:
            this.CGLIB$CALLBACK_0 = (MethodInterceptor)var2;
        default:
        }
    }

    public Callback[] getCallbacks() {
        CGLIB$BIND_CALLBACKS(this);
        return new Callback[]{this.CGLIB$CALLBACK_0};
    }

    public void setCallbacks(Callback[] var1) {
        this.CGLIB$CALLBACK_0 = (MethodInterceptor)var1[0];
    }

    static {
        CGLIB$STATICHOOK2();
    }
}

6.2 jdk

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

import com.rrc.finance.JavaProxyInterface;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;

public final class Ddd extends Proxy implements JavaProxyInterface {
    private static Method m1;
    private static Method m5;
    private static Method m3;
    private static Method m2;
    private static Method m4;
    private static Method m6;
    private static Method m0;

    public Ddd(InvocationHandler var1) throws  {
        super(var1);
    }

    public final boolean equals(Object var1) throws  {
        try {
            return (Boolean)super.h.invoke(this, m1, new Object[]{var1});
        } catch (RuntimeException | Error var3) {
            throw var3;
        } catch (Throwable var4) {
            throw new UndeclaredThrowableException(var4);
        }
    }

    public final void gotoSchool() throws  {
        try {
            super.h.invoke(this, m5, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final void oneDay() throws  {
        try {
            super.h.invoke(this, m3, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final String toString() throws  {
        try {
            return (String)super.h.invoke(this, m2, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final void oneDayFinal() throws  {
        try {
            super.h.invoke(this, m4, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final void gotoWork() throws  {
        try {
            super.h.invoke(this, m6, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final int hashCode() throws  {
        try {
            return (Integer)super.h.invoke(this, m0, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    static {
        try {
            m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
            m5 = Class.forName("com.rrc.finance.JavaProxyInterface").getMethod("gotoSchool");
            m3 = Class.forName("com.rrc.finance.JavaProxyInterface").getMethod("oneDay");
            m2 = Class.forName("java.lang.Object").getMethod("toString");
            m4 = Class.forName("com.rrc.finance.JavaProxyInterface").getMethod("oneDayFinal");
            m6 = Class.forName("com.rrc.finance.JavaProxyInterface").getMethod("gotoWork");
            m0 = Class.forName("java.lang.Object").getMethod("hashCode");
        } catch (NoSuchMethodException var2) {
            throw new NoSuchMethodError(var2.getMessage());
        } catch (ClassNotFoundException var3) {
            throw new NoClassDefFoundError(var3.getMessage());
        }
    }
}

 

可以看到cglib是直接继承了原有类,实现了Factory接口,而jdk是实现了自己的顶层接口,继承了Proxy接口。这里需要注意一下,这样的话,按照类来找话,jdk就找不到他的实现了,因为他的实现类实际上是一个Proxy类,而不是他自己。

这句话通俗点的意思,可以看下一小节。

7,Spring中使用的是哪种代理呢?

先上结论,如果一个类有顶层接口,则默认使用jdk的动态代理来代理,如果直接是一个类,则使用cglib动态代理。 其次,如果没有需要代理的方法,如所有方法都没有@Transactional注解,Aop这种,则不会被代理。

问题来了,只说结论,没有依据,怎么让人信服?

@Service
public class TestServiceImpl implements TestService {
    @Transactional
    public void updateActual() {
        
    }
    
}

在这里,我们实现一个Service,让他实现一个顶层接口,然后我们如果在Controller里使用

@Autowired
private TestServiceImpl testServiceImpl;

注解来注入,这时候会发现,启动时报错的。

报错也很明显:

The bean 'testServiceImpl' could not be injected as a 'com.rrc.finance.service.apply.TestServiceImpl' because it is a JDK dynamic proxy that implements:
	com.rrc.finance.service.apply.TestService

改成 :@Autowired
private  TestService  testServiceImpl; 

即可正常启动。

证明动态代理生成的代码是一个  TestService 却不是一个TestServiceImpl。使用的是jdk的动态代理。

这里去掉事务注解和 去掉接口实现 自己可以再试一下。

8,会了这些就完了吗?

在Spring的体系下,大多数的实现都在使用动态代理,我们可以通过他们优秀的源码来进行学习,来写一个自己的项目。

例如:Mybatis的mapper代理,分页插件的代理实现。Spring的Aop,事务注解等。

你可能感兴趣的:(动态代理,动态代理,cglib)