EnableAsync
1 | |
Enables Spring’s asynchronous method execution capability, similar to functionality found in Spring’s <task:*> XML namespace. To be used on @Configurationclasses as follows:
1 | |
where MyAsyncBeanis a user-defined type with one or methods annotated with @Async (or any custom annotation specified by the annotation() attribute).
The mode() attribute controls how advice is applied; if the mode is AdviceMode.PROXY (the default), then the other attributes control the behavior of the proxying.
Note that if the mode is set to AdviceMode.ASPECTJ, then the proxyTargetClass() attribute is obsolete. Note also that in this case the spring-aspectsmodule JAR must be present on the classpath.
By default, a SimpleAsyncTaskExecutor will be used to process async method invocations. To customize this behavior, implement AsyncConfigurer and provide your own Executor through the getExecutor() method.
1 | |
For reference, the example above can be compared to the following Spring XML configuration:
1 | |
the examples are equivalent save the setting of the thread name prefix of the Executor; this is because the the task:namespace executor element does not expose such an attribute. This demonstrates how the code-based approach allows for maximum configurability through direct access to actual componentry.
Note: In the above example the ThreadPoolTaskExecutor is not a fully managed Spring Bean. Add the @Bean annotation to the getAsyncExecutor()method if you want a fully managed bean. In such circumstances it is no longer necessary to manually call the executor.initialize() method as this will be invoked automatically when the bean is initialized.
解析
当mode是AdviceMode.PROXY时,proxyTargetClass决定是代理接口还是类,如果是接口,@Async必须是接口方法,否则可以是非接口方法。
1 | |
非面向接口编程也是可以的
1 | |
1 | |
当mode配置为AdviceMode.PROXY时,本地方法调用@Async无效,必须走代理@Async才有效。
1 | |
线程
默认线程池SimpleAsyncTaskExecutor,线程名SimpleAsyncTaskExecutor-1,SimpleAsyncTaskExecutor-2
QA
mode配置为AdviceMode.ASPECTJ,报错如下:
1 | |
新增依赖解决:
1 | |
当proxyTargetClass配置为false时,如下代码:
1 | |
运行时报错:
1 | |