- 前言
- 版本约定
- 正文
- AsyncAnnotationBeanPostProcessor
- AsyncAnnotationAdvisor
- AsyncAnnotationAdvisor 对应的 Pointcut
- AsyncAnnotationAdvisor 对应的 Advice: AnnotationAsyncExecutionInterceptor
- AnnotationAsyncExecutionInterceptor 的实现原理
- @Async 指定异步线程池运行
- @Async method 支持的返回类型
- @Async method 返回异常结果的处理
- 小结
系列博文:
【老王读Spring AOP-0】SpringAop引入&&AOP概念、术语介绍
【老王读Spring AOP-1】Pointcut如何匹配到 join point
【老王读Spring AOP-2】如何为 Pointcut 匹配的类生成动态代理类
【老王读Spring AOP-3】Spring AOP 执行 Pointcut 对应的 Advice 的过程
【老王读Spring AOP-4】Spring AOP 与Spring IoC 结合的过程 && ProxyFactory 解析
【老王读Spring AOP-5】@Transactional产生AOP代理的原理
【老王读Spring AOP-6】@Async产生AOP代理的原理
相关阅读:
【Spring源码三千问】Spring动态代理:什么时候使用的 cglib,什么时候使用的是 jdk proxy?
【Spring源码三千问】Advice、Advisor、Advised都是什么接口?
我们知道,@Async 是通过 Spring AOP 的方式来实现的。
前面讲了 Spring 中使用 @Transactional 的原理是通过定义 Advisor bean (BeanFactoryTransactionAttributeSourceAdvisor)的方式,让 AnnotationAwareAspectJAutoProxyCreator 帮助产生 AOP 动态代理类。
那么 @Async 的原理是不是也是定义一个 Advisor bean 呢?
这里先剧透一下:@Async 跟 @Transactional 使用 Spring AOP 的方式不太一样,@Async 是 new 一个 Advisor 来处理的,而不是定义一个 Advisor bean。
版本约定@Transactional产生AOP代理的原理请戳:https://blog.csdn.net/wang489687009/article/details/121214357
Spring 5.3.9 (通过 SpringBoot 2.5.3 间接引入的依赖)
正文Spring 中使用 AsyncAnnotationBeanPostProcessor 来处理 @Async 标记的类或方法,来生成相应的 AOP 代理类。
AsyncAnnotationBeanPostProcessorAsyncAnnotationBeanPostProcessor 的类图如下:
总结一个小技巧:
要看 Spring AOP 是如何实现某个特定的功能的话,就找到相应的 Advisor 是什么。
比如: 要看 @Transactional 是如何实现的,我们就可以找到 BeanFactoryTransactionAttributeSourceAdvisor .
首先找下 @Async 相应的 Advisor 是在哪里定义的:
// AsyncAnnotationBeanPostProcessor#setBeanFactory()
public void setBeanFactory(BeanFactory beanFactory) {
super.setBeanFactory(beanFactory);
// new 一个 AsyncAnnotationAdvisor
AsyncAnnotationAdvisor advisor = new AsyncAnnotationAdvisor(this.executor, this.exceptionHandler);
if (this.asyncAnnotationType != null) {
advisor.setAsyncAnnotationType(this.asyncAnnotationType);
}
advisor.setBeanFactory(beanFactory);
this.advisor = advisor;
}
AsyncAnnotationAdvisor
对于 Advisor,我们需要关注的有两个: 一是 Pointcut;二是 Advice
AsyncAnnotationAdvisor 对应的 Pointcut创建 Pointcut 的源码如下:
// AsyncAnnotationAdvisor#buildPointcut() protected Pointcut buildPointcut(Set> asyncAnnotationTypes) { ComposablePointcut result = null; for (Class extends Annotation> asyncAnnotationType : asyncAnnotationTypes) { // class pointcut: 匹配类上的 @Async 注解 Pointcut cpc = new AnnotationMatchingPointcut(asyncAnnotationType, true); // method pointcut: 匹配 method 上的 @Async 注解 Pointcut mpc = new AnnotationMatchingPointcut(null, asyncAnnotationType, true); if (result == null) { result = new ComposablePointcut(cpc); } else { result.union(cpc); } result = result.union(mpc); } return (result != null ? result : Pointcut.TRUE); }
可以看出,创建出的 Pointcut 会匹配类 或者 方法上的 @Async 注解,满足匹配条件的话,就会使用相应的 Advice 来生成代理类。
AsyncAnnotationAdvisor 对应的 Advice: AnnotationAsyncExecutionInterceptor// AsyncAnnotationAdvisor#buildAdvice() protected Advice buildAdvice(SupplierAnnotationAsyncExecutionInterceptor 的实现原理executor, Supplier exceptionHandler) { AnnotationAsyncExecutionInterceptor interceptor = new AnnotationAsyncExecutionInterceptor(null); interceptor.configure(executor, exceptionHandler); return interceptor; }
AnnotationAsyncExecutionInterceptor 是 @Async 方法实现异步执行的核心类。
// AsyncExecutionInterceptor#invoke()
public Object invoke(final MethodInvocation invocation) throws Throwable {
Class> targetClass = (invocation.getThis() != null ? AopUtils.getTargetClass(invocation.getThis()) : null);
Method specificMethod = ClassUtils.getMostSpecificMethod(invocation.getMethod(), targetClass);
final Method userDeclaredMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
// 选择指定的 AsyncTaskExecutor
AsyncTaskExecutor executor = determineAsyncExecutor(userDeclaredMethod);
if (executor == null) {
throw new IllegalStateException(
"No executor specified and no default executor set on AsyncExecutionInterceptor either");
}
// 将目标方法的执行封装成一个 Callable Task
Callable
总体来看,它的执行分为如下几步:
- 获取指定的 AsyncTaskExecutor
- 将目标方法的执行封装成一个 Callable Task
- 提交 task 任务到 AsyncTaskExecutor
@Async 可以通过 value 来指定使用哪个异步线程池来执行目标方法
相应的源码如下:
// AsyncAnnotationAdvisor#getExecutorQualifier()
protected String getExecutorQualifier(Method method) {
// Maintainer's note: changes made here should also be made in
// AnnotationAsyncExecutionAspect#getExecutorQualifier
Async async = AnnotatedElementUtils.findMergedAnnotation(method, Async.class);
if (async == null) {
async = AnnotatedElementUtils.findMergedAnnotation(method.getDeclaringClass(), Async.class);
}
return (async != null ? async.value() : null);
}
@Async method 支持的返回类型
@Async method 支持 4 种返回类型: void、CompletableFuture、ListenableFuture、Future
protected Object doSubmit(Callable@Async method 返回异常结果的处理
@Async method 返回异常的话,会交给 handleError() 来处理:
// AsyncExecutionAspectSupport#handleError()
protected void handleError(Throwable ex, Method method, Object... params) throws Exception {
if (Future.class.isAssignableFrom(method.getReturnType())) {
ReflectionUtils.rethrowException(ex);
} else {
// Could not transmit the exception to the caller with default executor
try {
this.exceptionHandler.obtain().handleUncaughtException(ex, method, params);
} catch (Throwable ex2) {
logger.warn("Exception handler for async method '" + method.toGenericString() +
"' threw unexpected exception itself", ex2);
}
}
}
可以看出:
- 对于 method 的返回类型是 Future 及子类的话,异常会直接抛出去,也就是抛到 Future#get() 的调用处
- 对于 method 的返回类型是 void 的话,异常会交给内部的 AsyncUncaughtExceptionHandler 来处理
@Async 是通过 AsyncAnnotationBeanPostProcessor 来产生 AOP 代理对象的。
@Async 相应的 Advisor 是 AsyncAnnotationAdvisor。
真正起作用的 Advice 是 AnnotationAsyncExecutionInterceptor。
@Async 可以通过 value 来指定使用的异步线程池。
@Async method 支持 4 种返回类型: void、CompletableFuture、ListenableFuture、Future
如果本文对你有所帮助,欢迎 点赞收藏!
老王读Spring IoC源码分析&测试代码下载
老王读Spring AOP源码分析&测试代码下载
有关 Spring 源码方面的问题欢迎一起交流,备注:CSDN (vx: Kevin-Wang001)



