Home >Java >javaTutorial >What is the default dynamic proxy method of SpringBoot/Spring AOP?

What is the default dynamic proxy method of SpringBoot/Spring AOP?

王林
王林forward
2023-05-10 15:52:183202browse

1. springboot 2.x and above

In SpringBoot 2.x AOP will be implemented by default using Cglib, but in Spring 5, jdk dynamic proxy is still used by default. Spring AOP uses JDK dynamic proxy by default. If the object does not implement the interface, CGLIB proxy is used. Of course, it is also possible to force the use of a CGLIB proxy.

In SpringBoot, AOP is automatically assembled through AopAutoConfiguration.

What is the default dynamic proxy method of SpringBoot/Spring AOP?

2. Springboot 1.x

Springboot 1.x AOP still uses JDK dynamic proxy by default

What is the default dynamic proxy method of SpringBoot/Spring AOP?

3. Why does SpringBoot 2.x use Cglib by default

Because JDK dynamic proxy is based on interfaces, the proxy is generated Objects can only be assigned to interface variables. JDK dynamic proxy uses Proxy.newProxyInstance() to create a proxy implementation class. However, the second parameter requires an interface type. If there is no interface type, an error will be reported.

Proxy.newProxyInstance(iCustomerInstance.getClass().getClassLoader(), iCustomerInstance.getClass().getInterfaces(), this);

CGLIB does not have this problem. Because CGLIB is implemented by generating subclasses, whether the proxy object is assigned to an interface or an implementation class, both are the parent classes of the proxy object.

So in version 2.x and above, the default implementation of AOP is changed to CGLIB proxy.

Create a new interface

public interface ICustomService {
    void printf();
}

Create a new implementation class of ICustomService

@Service
public class CustomServiceImpl implements ICustomService {
 
    public void printf() {
 
    }
}

Add another class that does not implement any interface

@Service
public class CustomNoImpl {
 
    public void hello() {
        
    }
}

Then start, you can use ICustomService and CustomNoImpl sees that the AOP proxy uses CGLIB's dynamic proxy

What is the default dynamic proxy method of SpringBoot/Spring AOP?

Then we set the proxy to the JDK proxy by default through application.properties configuration.

spring.aop.proxy-target-class=false

Then started debugging and found that CustomNoImpl uses the proxy generated by CGLIB because it does not implement the interface, while

customService has an interface implementation, so it uses the dynamic proxy of JDK

What is the default dynamic proxy method of SpringBoot/Spring AOP?

The above is the detailed content of What is the default dynamic proxy method of SpringBoot/Spring AOP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete