In our process of using the spring framework, many times we use @async annotations to execute some methods asynchronously to improve the efficiency of the system execution. Today we'll explore how spring is doing this.
1, spring scans the bean when the method contains @async annotations, if included, spring will dynamically generate a subclass for the bean, we call the proxy class (?).
2, the proxy class is to inherit the bean we write, and then inject the proxy class, in the execution of this method into the proxy class, the proxy class to determine that this method needs to execute asynchronously, will not invoke the parent class (we originally wrote the Bean) corresponding method.
3, spring to maintain a queue, he will need to execute the method, put into the queue, waiting for the thread pool to read this queue, complete the execution of the method, thus completing the asynchronous function.
Because of this implementation method in the same class as the method call, adding @async annotations is invalid! The reason is that when you are in the same class, the method call is executed inside the class, and spring cannot intercept the method call.
That's one step further, and spring provides us with AOP, aspect-oriented functionality. His principle and the principle of asynchronous annotations are similar:
When spring starts the container, it scans the class defined by the slice. When these classes are injected, the surrogate class is injected, and when you call these methods, it is essentially the proxy class that is called.
By executing the corresponding method of the parent class through the proxy class, spring only needs to execute a piece of code before and after the call to complete the implementation of the AOP!
Principles of Async Asynchronous annotations and annotations such as aspect facets annotations