Sping-AOP:cglib动态代理与JDK动态代理的区别

默认状态下,Spring-AOP默认使用JDK动态代理,当需要代理的对象没有实现任何接口时,才使用cglib动态代理。
下面,将向大家介绍JDK动态代理和Cglib动态代理的使用、两者的区别已经注意事项。

一、JDK动态代理

由于JDK动态代理是基于接口,所以我们先定义一个接口和该接口的实现。

//接口
package com.ghs.aop.proxy;

public interface TestService {

    void testMethod1();

    void testMethod2();
}

//接口的实现类
package com.ghs.aop.proxy.impl;

import com.ghs.aop.proxy.TestService;

public class TestServiceWithInterface implements TestService{

    @Override
    public void testMethod1() {
        System.out.println("With Interface: I'm the first method!");
    }

    @Override
    public void testMethod2() {
        System.out.println("With Interface: I'm the second method!");
    }

}

下面,我们定义一个切面。

package com.ghs.aop.proxy;

public class ProxyAspect {

    public void before(){
        System.out.println("前置通知!");
    }

    public void after(){
        System.out.println("后置通知!");
    }
}

对该切面进行AOP配置,如下:

<bean id="testServiceWithInterface" class="com.ghs.aop.proxy.impl.TestServiceWithInterface"></bean>

<bean id="proxyAspect" class="com.ghs.aop.proxy.ProxyAspect"></bean>
<aop:config>
    <aop:aspect ref="proxyAspect">
        <aop:pointcut expression="execution(* *.testMethod*(..))" id="proxyPointCut"/>
        <aop:before method="before" pointcut-ref="proxyPointCut"/>
        <aop:after method="after" pointcut-ref="proxyPointCut"/>
    </aop:aspect>
</aop:config>

执行我们的测试代码

public class TestProxy {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext-proxy.xml");
        TestService withInterface = (TestService) context.getBean("testServiceWithInterface");
        withInterface.testMethod1();
        withInterface.testMethod2();
    }
}

//运行结果如下:
前置通知!
With Interface: I'm the first method!
后置通知!
前置通知!
With Interface: I'm the second method!
后置通知!

我们需要注意下面几点:

  • 下面这句代码,只能将testServiceWithInterface对象强转为TestService,而不能强转为TestServiceWithInterface,因为JDK动态代理是基于接口的。

    TestService withInterface = (TestService) context.getBean("testServiceWithInterface");

二、Cglib动态代理

在上面的例子中,如果需要强制使用cglib进行动态代理,其实只需要改一下aop的配置。

<aop:config>......</aop:config>
改为
<aop:config proxy-target-class="true">......</aop:config>

其实默认情况下proxy-target-class值为false,此时,Spring-AOP默认使用JDK动态代理,当需要代理的对象没有实现任何接口时,才使用cglib动态代理。
当proxy-target-class设置为true时,Spring-AOP对需要代理的对象统一使用cglib动态代理。

在使用cglib动态代理时,需要注意下面几点:

  • 需要引入cglib的jar包,有两种方式,一是引入cglib.jar和asm.jar,二是引入cglib-nodep.jar
  • 对象的final方法无法被拦截
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值