> 本文作者:geek,一个聪明好学的朋友
## 1. 简介
开发中我们需要异步执行某个耗时任务时候需要@Async,以下我将从源码角度解释该注解的实现原理。
## 2.前提条件@EnableAsync
项目使用中,需要添加@EnableAsync注解支持,才能使用@Async(也支持自定义注解)生效。@EnableAsync(默认mode为AdviceMode.PROXY情况下)作用为了给spring项目加入AsyncConfigurationSelector,从而引入AsyncAnnotationBeanPostProcessor。
```java
@Import(AsyncConfigurationSelector.class)
public @interface EnableAsync {}
```
```java
public class ProxyAsyncConfiguration extends AbstractAsyncConfiguration {
@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");
/**
* 创建postProcessor,支持定制executor与exceptionHandler
*/
AsyncAnnotationBeanPostProcessor bpp = new 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;
}