@EnableAsync
时间: 2023-10-01 09:05:55 浏览: 56
@EnableAsync is a Spring annotation used to enable asynchronous method execution in a Spring application. When this annotation is added at the class level, Spring will automatically create a task executor and use it to execute the methods that are marked as asynchronous using the @Async annotation. This allows the methods to run in a separate thread, without blocking the main thread of the application.
To use @EnableAsync, you need to configure a task executor bean in your Spring application. Spring provides several built-in task executors such as ThreadPoolTaskExecutor and ConcurrentTaskExecutor. You can also create a custom task executor by implementing the TaskExecutor interface.
Example:
```
@Configuration
@EnableAsync
public class AppConfig {
@Bean(name = "taskExecutor")
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(2);
executor.setQueueCapacity(100);
executor.setThreadNamePrefix("Async-");
executor.initialize();
return executor;
}
}
```
In the above example, we have created a ThreadPoolTaskExecutor with a core pool size of 2, a maximum pool size of 2, and a queue capacity of 100. We have also set a thread name prefix to identify the threads created by this executor.
Now, we can mark any method as asynchronous using the @Async annotation:
```
@Service
public class MyService {
@Autowired
private MyRepository repository;
@Async
public void doSomethingAsync() {
// Method logic
}
// Other methods
}
```
In the above example, the doSomethingAsync() method will be executed asynchronously using the task executor configured in the AppConfig class.
相关推荐
![log](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)