Spring AOP Agent Details

  • 2021-12-11 18:39:07
  • OfStack

Spring AOP Agent Details

Foreword:

At first, I still knew and half-solved spring AOP. In the past few days, I encountered a problem, and I checked some knowledge about Spring. I felt that I had a deeper understanding of this problem. So write it down and share it for 1 time.

As we know, Spring supports several AOP modes, Spring's own proxy-based AOP and AspectJ's woven (weaving)-based AOP. Spring uses the default JDK dynamic proxy if a class implements one or more interfaces, or cglib if no interfaces are implemented. Of course, we can also change these settings manually. This is also the easy part to drop the pit. If the proxy mode is set incorrectly, BeanNotOfRequiredTypeException will appear during dependency injection.

First of all, let's talk about JDK dynamic proxy, which will proxy interface. Specifically, the object A implements the interface A and the interface B. Spring creates a proxy object that implements the interfaces A and B, but note that the proxy object has no relationship to the object A. We can use the proxy object as any one interface, but we cannot convert the proxy object to the class A for use.

Suppose we now have the following 1 interface and class.


public interface InterfaceA {
}

public class ClassA implements InterfaceA {
}

Then if we use dependency injection to get the object A, the type can only be InterfaceA, and if the type is ClassA, BeanNotOfRequiredTypeException will appear. Because the actual injected object here is a proxy object that implements InterfaceA and has nothing to do with ClassA. This situation is recommended by Spring, and we use interfaces to program. If you have to inject classes, you need to use cglib as proxy, which is to add proxy-target-class= "true" to the AOP configuration.

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

Finally, let's talk about the weaving-based AOP of AspectJ. The so-called weaving is to add or modify code in the generated class file, which can be divided into compile-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. Because of the weaving-based features of AspectJ, the self-reference of AOP based on proxy, and the problems of both proxies will not appear in AspectJ.

Thank you for reading, hope to help everyone, thank you for your support to this site!


Related articles: