English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Detailed introduction to Spring AOP proxy

Detailed introduction to Spring AOP proxy

Preface:

At first, I was still in a state of knowing little about Spring AOP. These days, I encountered a problem, and after reviewing some related knowledge of Spring, I feel that I have a deeper understanding of this issue. Therefore, I write it down to share with everyone.

We know that Spring supports multiple AOP approaches, including Spring's own proxy-based AOP and AspectJ's weaving-based AOP. If a class implements one or more interfaces, Spring will use the default JDK dynamic proxy. If no interfaces are implemented, cglib will be used for proxying. Of course, we can also manually change these settings. This is also a part that is relatively easy to fall into a pit, as if the proxying method is set incorrectly, a BeanNotOfRequiredTypeException will occur during dependency injection.

Let's talk about JDK dynamic proxy first. This proxy method will proxy interfaces. Specifically, object A implements interfaces A and B. Spring will create a proxy object that implements interfaces A and B, but it should be noted that there is no relationship between the proxy object and object A. We can treat the proxy object as any interface, but we cannot use the proxy object as ClassA.

Suppose we have the following interface and class now.

public interface InterfaceA {
}
public class ClassA implements InterfaceA {
}

Then if we use dependency injection to obtain object A, the type can only be InterfaceA, and if the type is written as ClassA, a BeanNotOfRequiredTypeException will occur. Because the actual injected object is an proxy object that implements InterfaceA, which has nothing to do with ClassA. This is a situation recommended by Spring, using interfaces for programming. If it is necessary to inject a class, you need to use cglib to proxy, that is, to add proxy in the AOP configuration.-target-class="true".

Then let's talk about cglib proxy. This is a proxy class method, so if we use this proxy, we can inject ClassA and InterfaceA in the above situation.

Let's talk about AspectJ's weaving-based AOP first. Weaving refers to adding or modifying code in the generated class files, which can be compiled-time weaving and runtime weaving. If you use AspectJ and decompile a woven class, you will find that the class file has been modified by AspectJ. Due to the weaving-based characteristics of AspectJ, issues such as self-reference, and two proxy problems that occur in proxy-based AOP will not appear in AspectJ.

Thank you for reading, I hope it can help everyone. Thank you for your support of this site!

You May Also Like