春天的靴子。如何使用注释创建TaskExecutor? [英] Spring boot. How to Create TaskExecutor with Annotation?
问题描述
我在Spring Boot应用程序中执行了一个 @Service
类,其中一个方法应该是异步运行的。因为我读取方法应该 @Async
注释,我还必须运行 TaskExecutor
bean。但是在Spring手册中 http://docs.spring .io / spring / docs / current / spring-framework-reference / html / scheduling.html 我找不到任何关于如何使用注释运行 TaskExecutor
的信息或示例,没有XML配置。是否可以在没有XML的Spring Boot中创建 TaskExecutor
bean,仅注释?这里是我的服务类:
I did a @Service
class in Spring Boot application with one of the methods that should run asynchronously. As I read method should be @Async
annotated and also I have to run a TaskExecutor
bean. But in Spring manual http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html I not find any info or example how to run TaskExecutor
with annotation, without XML config. Is it possible to create TaskExecutor
bean in Spring Boot without XML, with annotations only? Here my Service class:
@Service
public class CatalogPageServiceImpl implements CatalogPageService {
@Override
public void processPagesList(List<CatalogPage> catalogPageList) {
for (CatalogPage catalogPage:catalogPageList){
processPage(catalogPage);
}
}
@Override
@Async("locationPageExecutor")
public void processPage(CatalogPage catalogPage) {
System.out.println("print from Async method "+catalogPage.getUrl());
}
}
推荐答案
添加Spring Boot应用程序类的 @Bean
方法:
Add a @Bean
method to your Spring Boot application class:
@SpringBootApplication
@EnableAsync
public class MySpringBootApp {
@Bean
public TaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(5);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(25);
return executor;
}
public static void main(String[] args) {
// ...
}
}
参见基于Java的容器配置,关于如何使用Java配置而不是XML配置Spring。
See Java-based container configuration in the Spring Framework reference documentation on how to configure Spring using Java config instead of XML.
(注意:您不需要在课程中添加 @Configuration
,因为 @SpringBootApplication
已包含 @Configuration
)。
(Note: You don't need to add @Configuration
to the class because @SpringBootApplication
already includes @Configuration
).
这篇关于春天的靴子。如何使用注释创建TaskExecutor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!