1. springboot 2.x 及以上版本
在 springboot 2.x aop中会默认使用cglib来实现,但是spring5中默认还是使用jdk动态代理。spring aop 默认使用 jdk 动态代理,如果对象没有实现接口,则使用 cglib 代理。当然,也可以强制使用 cglib 代理。
在 SpringBoot 中,通过AopAutoConfiguration来自动装配AOP.

2. Springboot 1.x
Springboot 1.x AOP默认还是使用 JDK 动态代理的

3.SpringBoot 2.x 为何默认使用 Cglib
因为JDK 动态代理是基于接口的,代理生成的对象只能赋值给接口变量。JDK动态代理使用Proxy.newProxyInstance()创建代理实现类,然而第二个参数就需要接口类型,如果没有接口类型就会报错。
Proxy.newProxyInstance(iCustomerInstance.getClass().getClassLoader(), iCustomerInstance.getClass().getInterfaces(), this);
而 CGLIB 就不存在这个问题。因为 CGLIB 是通过生成子类来实现的,代理对象无论是赋值给接口还是实现类,这两者都是代理对象的父类。
所以在2.x版本以上,将 AOP 默认实现改为了 CGLIB代理。
新建一个接口
public interface ICustomService {
void printf();
}新建一个ICustomService的实现类
@Service
public class CustomServiceImpl implements ICustomService {
public void printf() {
}
}再增加一个类不实现任何接口
@Service
public class CustomNoImpl {
public void hello() {
}
}然后启动,可以ICustomService和CustomNoImpl看出AOP的代理使用的是CGLIB的动态代理

然后我们通过application.properties配置将代理默认设置为JDK代理。
spring.aop.proxy-target-class=false
然后启动调试发现,CustomNoImpl因为没有实现接口,所以使用的是CGLIB生成的代理,而
customService有接口实现,所以使用JDK的动态代理









