@Async can also be used at the class level, in which case all of the class methods will be executed asynchronously.
package com.logicbig.example; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; @Component @Async public class MyBean { public void runTask1() { System.out.printf("runTask1 thread: %s%n", Thread.currentThread().getName()); } public void runTask2() { System.out.printf("runTask2 thread: %s%n", Thread.currentThread().getName()); } }
package com.logicbig.example; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.core.task.TaskExecutor; import org.springframework.scheduling.annotation.EnableAsync; import org.springframework.scheduling.concurrent.ConcurrentTaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; @EnableAsync @ComponentScan public class AsyncExample { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( AsyncExample.class); MyBean bean = context.getBean(MyBean.class); System.out.printf("calling async method from thread: %s%n", Thread.currentThread().getName()); bean.runTask1(); bean.runTask2(); } }
calling async method from thread: com.logicbig.example.AsyncExample.main()runTask1 thread: SimpleAsyncTaskExecutor-1runTask2 thread: SimpleAsyncTaskExecutor-2
Dependencies and Technologies Used:
Version compatibilities of spring-context with this example:
Versions in green have been tested.