EnableAsync分析
一、EnableAsync介绍
同Configuration注解配合使用,以切面方式,为Spring应用程序,开启注解驱动异步执行。
1、线程池选择
默认寻找TaskExecutor bean,或名称为taskExecutor的Executor,作为线程池。若没有提供,则使用SimpleAsyncTaskExecutor作为线程池。
另外,可实现AsyncConfigurer接口,定制化Executor、AsyncUncaughtExceptionHandler,用于自定义线程池以及异常信息处理。
2、代理模式选择
EnableAsync.mode,若选择AdviceMode.PROXY,将基于代理拦截器方式拦截调用,该模式下,本地方法调用不会生效。
EnableAsync.mode,若选择AdviceMode.ASPECTJ,需提供spring-aspects模块依赖,该模式下,本地方法调用会被拦截。
二、涉及类分析
1.AsyncConfigurationSelector
通过EnableAsync注解上的Import注解引入。用于EnableAsync.mode属性,选择不同的处理类,开启异步处理。
EnableAsync.mode=AdviceMode.PROXY时,使用ProxyAsyncConfiguration配置类。
EnableAsync.mode=AdviceMode.ASPECTJ时,使用AspectJAsyncConfiguration配置类
// AdviceModeImportSelector
@Override
public final String[] selectImports(AnnotationMetadata importingClassMetadata) {
// 通过实现类上的泛型,确定作用的注解。
Class<?> annType = GenericTypeResolver.resolveTypeArgument(getClass(), AdviceModeImportSelector.class);
Assert.state(annType != null, "Unresolvable type argument for AdviceModeImportSelector");
AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(importingClassMetadata, annType);
if (attributes == null) {
throw new IllegalArgumentException(String.format(
"@%s is not present on importing class '%s' as expected",
annType.getSimpleName(), importingClassMetadata.getClassName()));
}
// 通过注解,获取其所使用的AdviceMode类型。
AdviceMode adviceMode = attributes.getEnum(getAdviceModeAttributeName());
String[] imports = selectImports(adviceMode);
if (imports == null) {
throw new IllegalArgumentException("Unknown AdviceMode: " + adviceMode);
}
return imports;
}
// AsyncConfigurationSelector
@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;
}
}
2.ProxyAsyncConfiguration
收集AsyncConfigurer配置类,存在多个时,取第一个,获取线程池和异常信息处理类。基于线程池和异常信息处理类,构建AsyncAnnotationBeanPostProcessor。
// AsyncAnnotationBeanPostProcessor
@Bean(name = TaskManagementConfigUtils.ASYNC_ANNOTATION_PROCESSOR_BEAN_NAME)
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
public AsyncAnnotationBeanPostProcessor asyncAdvisor() {
Assert.notNull(this.enableAsync, "@EnableAsync annotation metadata was not injected");
AsyncAnnotationBeanPostProcessor bpp = new AsyncAnnotationBeanPostProcessor();
// 使用抽象类中,获取到的线程池以及异常信息处理类,一同构建AsyncAnnotationBeanPostProcessor。
bpp.configure(this.executor, this.exceptionHandler);
Class<? extends Annotation> customAsyncAnnotation = this.enableAsync.getClass("annotation");
if (customAsyncAnnotation != AnnotationUtils.getDefaultValue(EnableAsync.class, "annotation")) {
bpp.setAsyncAnnotationType(customAsyncAnnotation);
}
bpp.setProxyTargetClass(this.enableAsync.getBoolean("proxyTargetClass"));
bpp.setOrder(this.enableAsync.<Integer>getNumber("order"));
return bpp;
}
3.AsyncAnnotationBeanPostProcessor
BeanPostProcessor实现类,对指定的类,提供AOP切面支持。若当前Bean为Advised实现类,通过beforeExistingAdvisors属性,用于确定,添加切面的顺序。若不是,则基于ProxyFactory生成代理类,并添加拦截器。
AsyncAnnotationBeanPostProcessor继承AbstractBeanFactoryAwareAdvisingPostProcessor,覆写setBeanFactory,基于AsyncAnnotationAdvisor提供切面定义。
// AbstractAdvisingBeanPostProcessor
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
if (this.advisor == null || bean instanceof AopInfrastructureBean) {
// Ignore AOP infrastructure such as scoped proxies.
return bean;
}
// 若Bean为Advised实现类,则添加Advised。
if (bean instanceof Advised) {
Advised advised = (Advised) bean;
if (!advised.isFrozen() && isEligible(AopUtils.getTargetClass(bean))