结论

proxy-target-class=”true”,使用CGLIB代理
proxy-target-class=”false”,使用JDK代理,默认是JDK代理

使用场景

spring的代理模式有两种,JDK和CGLIB
jdk适用于目标类有接口的情况;
cglib适用于目标类没有接口,是普通类的情况;

配置

applicationContext.xml

<context:component-scan base-package="testmaven.service"></context:component-scan>

    <bean id="myinterceptor" class="testmaven.interceptor.MyInterceptor"></bean>

    <aop:config proxy-target-class="false">
        <aop:pointcut expression="execution(*  testmaven.service.*.*(..))" id="mypointcut"/>
        <aop:advisor advice-ref="myinterceptor" pointcut-ref="mypointcut"/>
    </aop:config>

Interceptor代码

public class MyInterceptor implements MethodBeforeAdvice {

    public void before(Method arg0, Object[] arg1, Object arg2)
            throws Throwable {
        System.out.println("aop before.....");
    }

}

service代码

public interface MyService {

    void sayHello();
}

service实现代码

@Service
public class MyServiceImpl implements MyService {

    public void sayHello() {
        System.out.println("hello buddy");
    }

}

测试代码

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(value={"classpath:applicationContext.xml"})
public class TestProxyTargetClass {

    @Autowired
    MyService myService;

    @Test
    public void jdkProxy(){
        System.out.println(myService);
        System.out.println(myService.getClass());
        myService.sayHello();
    }
}

目录视图

spring proxy-target-class_System

proxy-target-class=”false”

proxy-target-class=”false”,表示使用jdk代理方式。获取bean,打印出来的是$Proxy13

打印结果

testmaven.service.impl.MyServiceImpl@3743ff5e
class com.sun.proxy.$Proxy13
aop before.....
hello buddy

proxy-target-class=”true”

proxy-target-class=”true”,表示适用cglib代理方式。获取bean,打印出来的是BeanName$EnhancerBySpringCGLIB。

打印结果

testmaven.service.impl.MyServiceImpl@196f4737
class testmaven.service.impl.MyServiceImpl$$EnhancerBySpringCGLIB$$ef8fd010
aop before.....
hello buddy