Spring framework版本 5.3.x
1. 异步核心类
![EnableAsync关系]
-
@EnableAsync
开启Spring的异步功能
-
AsyncConfigurationSelector
导入异步功能的配置和处理相关的类
-
ProxyAsyncConfiguration
代理异步配置类,设置了执行线程池、异步错误的处理器,以及AOP相关的三个类
-
AsyncAnnotationBeanPostProcessor
处理标记了@Async类和方法(也就是Spring AOP)
-
AOP的三大组件
AsyncAnnotationAdvisor、AnnotationMatchingPointcut、AnnotationAsyncExecutionInterceptor
2. 源码分析
2.1 @EnableAsync源码解析
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(AsyncConfigurationSelector.class)
public @interface EnableAsync {
//设置自定义的注解
Class<? extends Annotation> annotation() default Annotation.class;
boolean proxyTargetClass() default false;
AdviceMode mode() default AdviceMode.PROXY;
int order() default Ordered.LOWEST_PRECEDENCE;
}
复制代码
从上面可以看出主要使用了 AsyncConfigurationSelector
来导入选择导入配置类,下面来看一下
2.2 AsyncConfigurationSelector源码解析
public class AsyncConfigurationSelector extends AdviceModeImportSelector<EnableAsync> {
private static final String ASYNC_EXECUTION_ASPECT_CONFIGURATION_CLASS_NAME =
"org.springframework.scheduling.aspectj.AspectJAsyncConfiguration";
@Override
@Nullable
public String[] selectImports(AdviceMode adviceMode) {
switch (adviceMode) {
case PROXY:
return new String[] {ProxyAsyncConfiguration.class.getName()};
case ASPECTJ:
return new String[] {ASYNC_EXECUTION_ASPECT_CONFIGURATION_CLASS_NAME};
default:
return null;
}
}
}
复制代码
在这里主要导入了配置 ProxyAsyncConfiguration
。这个类主要的作用也是导入配置类。接着来看一下配置类。
2.3 ProxyAsyncConfiguration源码解析
@Configuration(proxyBeanMethods = false)
@Role(Bea