Spring AOP proxy, Spring AOP
Spring AOP proxy
Preface:
At the beginning, I still had a thorough understanding of spring AOP. I encountered a problem in the past few days and checked some Spring-related knowledge. I felt that I had a deeper understanding of this issue. So write it down and share it.
We know that Spring supports multiple AOP methods. Spring's own proxy-based AOP and AspectJ's weaving-based AOP. If a class implements one or more interfaces, Spring uses the default JDK dynamic proxy. If no interfaces are implemented, cglib is used as the proxy. Of course, you can also manually change these settings. This is also a relatively easy part to fall into. If the proxy method is set incorrectly, BeanNotOfRequiredTypeException will occur during dependency injection.
JDK dynamic proxy is used as a proxy interface. Specifically, object A implements interfaces A and B. Spring will create A proxy object, which implements interfaces A and B. However, it should be noted that the proxy object and object A have no relationship. We can use the proxy object as any interface, but we cannot convert the proxy object to Class.
Assume that we now have the next interface and class.
public interface InterfaceA {}public class ClassA implements InterfaceA {}
Then, if we use dependency injection to obtain object A, the type can only be InterfaceA. If the type is written as ClassA, BeanNotOfRequiredTypeException will occur. Because the actually injected object is a proxy object implementing InterfaceA, it has nothing to do with ClassA. In this case, we recommend that you use interfaces for programming. If the class must be injected, cglib must be used for proxy, that is, proxy-target-class = "true" must be added to the AOP configuration ".
Then let's talk about the cglib proxy. This is a proxy class, so if we use this proxy, we can inject both ClassA and InterfaceA.
Finally, let's talk about AspectJ's weaving-based AOP. The so-called weaving means to add or modify code in the generated class file, which can be divided into compiling and runtime weaving. If you use AspectJ and decompile a braided class, you will find that this class file has been modified by AspectJ. Due to the weaving-based feature of AspectJ, the self-reference of proxy-based AOP and the problems of the two proxies will not occur in AspectJ.
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!