The working principle of spring-aop agent

Let's mainly talk about the principle of aop in spring, not the underlying cglib and gdk dynamic agents.

It is still the old analysis process. First, find the handler of the aop tag, and then look at what was done when parsing the tag. In fact, the main thing is to see which beans are registered and which beanPostProcessors. Because I have seen so many The functional realization of spring is basically done through these beanPostProcessors, and this should be no exception.

Ok, you will see at first glance, assemble our configured pointCut, advice, etc. into a beanDefinition and register with the container. The main function of these beans is to record the data we configured (pointcut, target class, intercepter class, etc.), and Not a very important part. Then I saw that a class was registered: AspectJAwareAdvisorAutoProxyCreator, this class is the core of aop in spring.

Looking at the inheritance relationship, I found that it implements the beanPostProcessor interface, ok, it is the same as our initial guess, and then look at the implementation inside, and then the specific implementation inside, I will not write it in detail, in general The process is like this.

 

A bean starts to be instantiated—> call the callback interface of the instantiated bean in AspectJAwareAdvisorAutoProxyCreator to see if the bean can be instantiated in advance, create a proxy, and then return to the final proxy class—> After the above failure, follow the normal instantiation process— > After the bean instance is initialized, call the beanpostProcessor callback interface of AspectJAwareAdvisorAutoProxyCreator—> If all advisor instances have not been obtained, first obtain all advisor instances in the container, and then use the for loop to determine whether the current bean should be proxied or not. If it should, return directly -> According to the information in the advisor, start proxying the bean. Note that if the bean has multiple advisors, the applicable advisors will be taken out here as the interceptor in the proxy, and then choose which one to use. This proxy method performs the underlying proxy process, and finally returns the proxied class.

 

It should be noted here that AspectJAwareAdvisorAutoProxyCreator must be instantiated before other ordinary beans. Then, looking back at the process of container initialization, it is true that all processors will be instantiated first, and then ordinary beans will be instantiated last. What kind of beans will be instantiated and what kind of beans will be instantiated lazily, which has been specifically mentioned in the previous article, so I won't talk about it here. ps: The instantiation priority can also be set inside these beanPostProcessors. The high priority will be initialized first. This is sometimes more important and needs to be paid attention to.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325058139&siteId=291194637