Java 弹簧靴。如何使用注解创建 TaskExecutor?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38370063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring boot. How to Create TaskExecutor with Annotation?
提问by Pavlo
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.htmlI 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
在 Spring Boot 应用程序中做了一个类,其中一个方法应该异步运行。当我阅读方法时,应该对方法进行@Async
注释,而且我必须运行一个TaskExecutor
bean。但是在 Spring 手册http://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html 中,我没有找到任何信息或示例如何在TaskExecutor
没有 XML 配置的情况下使用注释运行。是否可以TaskExecutor
在没有 XML 的情况下在 Spring Boot 中创建bean,仅使用注释?这是我的服务类:
@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());
}
}
采纳答案by Jesper
Add a @Bean
method to your Spring Boot application class:
@Bean
向 Spring Boot 应用程序类添加一个方法:
@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) {
// ...
}
}
See Java-based container configurationin the Spring Framework reference documentation on how to configure Spring using Java config instead of XML.
有关如何使用 Java 配置而不是 XML 配置 Spring 的信息,请参阅Spring Framework 参考文档中的基于 Java 的容器配置。
(Note: You don't need to add @Configuration
to the class because @SpringBootApplication
already includes @Configuration
).
(注意:您不需要添加@Configuration
到类中,因为@SpringBootApplication
已经包含了@Configuration
)。
回答by Igor Shevchenko
First – let's go over the rules – @Async has two limitations:
首先——让我们回顾一下规则——@Async 有两个限制:
- it must be applied to public methods only
- self-invocation – calling the async method from within the same class – won't work
- 它必须只应用于公共方法
- 自调用——从同一个类中调用异步方法——将不起作用
So your processPage() method should be in separate class
所以你的 processPage() 方法应该在单独的类中