spring-framework / org.springframework.scheduling.annotation / EnableAsync

EnableAsync

@Target([AnnotationTarget.CLASS, AnnotationTarget.FILE]) @Import(AsyncConfigurationSelector) class EnableAsync

Enables Spring's asynchronous method execution capability, similar to functionality found in Spring's <task:*> XML namespace.

To be used together with @Configuration classes as follows, enabling annotation-driven async processing for an entire Spring application context:

 @Configuration @EnableAsync public class AppConfig { }
MyAsyncBean is a user-defined type with one or more methods annotated with either Spring's @Async annotation, the EJB 3.1 @javax.ejb.Asynchronous annotation, or any custom annotation specified via the #annotation attribute. The aspect is added transparently for any registered bean, for instance via this configuration:
 @Configuration public class AnotherAppConfig { @Bean public MyAsyncBean asyncBean() { return new MyAsyncBean(); } }

By default, Spring will be searching for an associated thread pool definition: either a unique org.springframework.core.task.TaskExecutor bean in the context, or an java.util.concurrent.Executor bean named "taskExecutor" otherwise. If neither of the two is resolvable, a org.springframework.core.task.SimpleAsyncTaskExecutor will be used to process async method invocations. Besides, annotated methods having a void return type cannot transmit any exception back to the caller. By default, such uncaught exceptions are only logged.

To customize all this, implement AsyncConfigurer and provide:

 @Configuration @EnableAsync public class AppConfig implements AsyncConfigurer { @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(7); executor.setMaxPoolSize(42); executor.setQueueCapacity(11); executor.setThreadNamePrefix("MyExecutor-"); executor.initialize(); return executor; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return MyAsyncUncaughtExceptionHandler(); } }

If only one item needs to be customized, null can be returned to keep the default settings. Consider also extending from AsyncConfigurerSupport when possible.

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.

For reference, the example above can be compared to the following Spring XML configuration:

<beans> <task:annotation-driven executor="myExecutor" exception-handler="exceptionHandler"/> <task:executor id="myExecutor" pool-size="7-42" queue-capacity="11"/> <bean id="asyncBean" class="com.foo.MyAsyncBean"/> <bean id="exceptionHandler" class="com.foo.MyAsyncUncaughtExceptionHandler"/> </beans> 
The above XML-based and JavaConfig-based examples are equivalent except for the setting of the thread name prefix of the Executor; this is because the <task:executor> element does not expose such an attribute. This demonstrates how the JavaConfig-based approach allows for maximum configurability through direct access to actual componentry.

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. Please note that proxy mode allows for interception of calls through the proxy only; local calls within the same class cannot get intercepted that way.

Note that if the #mode is set to AdviceMode#ASPECTJ, then the value of the #proxyTargetClass attribute will be ignored. Note also that in this case the spring-aspects module JAR must be present on the classpath, with compile-time weaving or load-time weaving applying the aspect to the affected classes. There is no proxy involved in such a scenario; local calls will be intercepted as well.

Author
Chris Beams

Author
Juergen Hoeller

Author
Stephane Nicoll

Author
Sam Brannen

Since
3.1

See Also
AsyncAsyncConfigurerAsyncConfigurationSelector

Constructors

<init>

EnableAsync(annotation: KClass<out Annotation>, proxyTargetClass: Boolean, mode: AdviceMode, order: Int)

Enables Spring's asynchronous method execution capability, similar to functionality found in Spring's <task:*> XML namespace.

To be used together with @Configuration classes as follows, enabling annotation-driven async processing for an entire Spring application context:

 @Configuration @EnableAsync public class AppConfig { }
MyAsyncBean is a user-defined type with one or more methods annotated with either Spring's @Async annotation, the EJB 3.1 @javax.ejb.Asynchronous annotation, or any custom annotation specified via the #annotation attribute. The aspect is added transparently for any registered bean, for instance via this configuration:
 @Configuration public class AnotherAppConfig { @Bean public MyAsyncBean asyncBean() { return new MyAsyncBean(); } }

By default, Spring will be searching for an associated thread pool definition: either a unique org.springframework.core.task.TaskExecutor bean in the context, or an java.util.concurrent.Executor bean named "taskExecutor" otherwise. If neither of the two is resolvable, a org.springframework.core.task.SimpleAsyncTaskExecutor will be used to process async method invocations. Besides, annotated methods having a void return type cannot transmit any exception back to the caller. By default, such uncaught exceptions are only logged.

To customize all this, implement AsyncConfigurer and provide:

 @Configuration @EnableAsync public class AppConfig implements AsyncConfigurer { @Override public Executor getAsyncExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(7); executor.setMaxPoolSize(42); executor.setQueueCapacity(11); executor.setThreadNamePrefix("MyExecutor-"); executor.initialize(); return executor; } @Override public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() { return MyAsyncUncaughtExceptionHandler(); } }

If only one item needs to be customized, null can be returned to keep the default settings. Consider also extending from AsyncConfigurerSupport when possible.

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.

For reference, the example above can be compared to the following Spring XML configuration:

<beans> <task:annotation-driven executor="myExecutor" exception-handler="exceptionHandler"/> <task:executor id="myExecutor" pool-size="7-42" queue-capacity="11"/> <bean id="asyncBean" class="com.foo.MyAsyncBean"/> <bean id="exceptionHandler" class="com.foo.MyAsyncUncaughtExceptionHandler"/> </beans> 
The above XML-based and JavaConfig-based examples are equivalent except for the setting of the thread name prefix of the Executor; this is because the <task:executor> element does not expose such an attribute. This demonstrates how the JavaConfig-based approach allows for maximum configurability through direct access to actual componentry.

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. Please note that proxy mode allows for interception of calls through the proxy only; local calls within the same class cannot get intercepted that way.

Note that if the #mode is set to AdviceMode#ASPECTJ, then the value of the #proxyTargetClass attribute will be ignored. Note also that in this case the spring-aspects module JAR must be present on the classpath, with compile-time weaving or load-time weaving applying the aspect to the affected classes. There is no proxy involved in such a scenario; local calls will be intercepted as well.

Properties

annotation

val annotation: KClass<out Annotation>

Indicate the 'async' annotation type to be detected at either class or method level.

By default, both Spring's @Async annotation and the EJB 3.1 @javax.ejb.Asynchronous annotation will be detected.

This attribute exists so that developers can provide their own custom annotation type to indicate that a method (or all methods of a given class) should be invoked asynchronously.

mode

val mode: AdviceMode

Indicate how async advice should be applied.

The default is AdviceMode#PROXY. Please note that proxy mode allows for interception of calls through the proxy only. Local calls within the same class cannot get intercepted that way; an Async annotation on such a method within a local call will be ignored since Spring's interceptor does not even kick in for such a runtime scenario. For a more advanced mode of interception, consider switching this to AdviceMode#ASPECTJ.

order

val order: Int

Indicate the order in which the AsyncAnnotationBeanPostProcessor should be applied.

The default is Ordered#LOWEST_PRECEDENCE in order to run after all other post-processors, so that it can add an advisor to existing proxies rather than double-proxy.

proxyTargetClass

val proxyTargetClass: Boolean

Indicate whether subclass-based (CGLIB) proxies are to be created as opposed to standard Java interface-based proxies.

Applicable only if the #mode is set to AdviceMode#PROXY.

The default is false.

Note that setting this attribute to true will affect all Spring-managed beans requiring proxying, not just those marked with @Async. For example, other beans marked with Spring's @Transactional annotation will be upgraded to subclass proxying at the same time. This approach has no negative impact in practice unless one is explicitly expecting one type of proxy vs. another — for example, in tests.