The scenario is as follows:
Service calls to lower-level modules respond slowly, so asynchronous thread calls are changed to prevent blocking others' threads.Copy the code
Original code:
if (XXXX) {
async(XXXXX);
}
@Async("asyncExecutor")
public void async(XXXX) {
XXXX
}
Copy the code
There is a problem
Async annotations fail mainly because Async is implemented based on Spring AOP, which is based on the proxy pattern. Since Async is called by itself, instead of using proxy classes, it does not go through the Spring container.Copy the code
The solution
if (XXX) { XXXServiceImpl XXXService = SpringContextUtil.getBeanOfType(XXXServiceImpl.class); async(XXXXX); } @async ("asyncExecutor") public void Async(XXXX) {XXXX} 2020/07/02 15:47:33.76134b3d3bF-60fa-43d9-a799-9bf46011fd0b asyncExecutor-1 [INFO] XXXServiceImpl (XXXServiceImpl.java:197)Copy the code
Solutions that
1. Annotation methods must be public methods. 2. Methods must be called from another class, that is, from outside the class. Calls from inside the class are invalid. 3. If you need to call from inside a class, you need to get its proxy class first. This method is described above, and the corresponding bean is obtained by using ApplicationContext. 4. Add the @enableAsync annotation to the startup class.Copy the code