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

来源:互联网 发布:c语言产生0 1的随机数 编辑:程序博客网 时间:2024/06/08 14:14

默认状态下,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方法无法被拦截
0 0
原创粉丝点击