java – 升级到Spring Boot 1.3.3后@Async无法正常工作

前端之家收集整理的这篇文章主要介绍了java – 升级到Spring Boot 1.3.3后@Async无法正常工作前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有一个在Spring Boot 1.2.3下运行的应用程序,它使用@Async注释的方法.到目前为止,它一直在正常工作.

升级到Spring Boot 1.3.3后,标记为@Async的方法不会在单独的线程中调用.

这是一个说明问题的示例程序:

App.java:

  1. package test;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.boot.CommandLineRunner;
  6. import org.springframework.boot.SpringApplication;
  7. import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
  8. import org.springframework.context.annotation.ComponentScan;
  9. import org.springframework.context.annotation.Configuration;
  10. import org.springframework.scheduling.annotation.EnableAsync;
  11. @Configuration
  12. @EnableAutoConfiguration
  13. @ComponentScan(basePackages = { "test" })
  14. @EnableAsync
  15. public class App implements CommandLineRunner {
  16. private static final Logger log = LoggerFactory.getLogger(App.class);
  17. @Autowired
  18. AsyncClass async;
  19. public static void main(String[] args) {
  20. SpringApplication.run(App.class,args);
  21. }
  22. public void run(String... arg0) throws Exception {
  23. log.info("in run");
  24. async.start();
  25. log.info("done run");
  26. }
  27. }
  28. @H_404_13@

AsyncClass.java:

  1. package test;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.scheduling.annotation.Async;
  6. import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
  7. import org.springframework.stereotype.Component;
  8. @Component
  9. public class AsyncClass {
  10. private static final Logger log = LoggerFactory.getLogger(AsyncClass.class);
  11. @Async("myTaskExecutor")
  12. public void start() {
  13. log.info("in async task");
  14. try {
  15. Thread.sleep(2000);
  16. } catch (InterruptedException e) { }
  17. log.info("done async task");
  18. }
  19. @Bean
  20. public ThreadPoolTaskExecutor myTaskExecutor() {
  21. ThreadPoolTaskExecutor bean = new ThreadPoolTaskExecutor();
  22. bean.setCorePoolSize(1);
  23. bean.setMaxPoolSize(1);
  24. bean.setQueueCapacity(10);
  25. bean.setThreadPriority(1);
  26. bean.setWaitForTasksToCompleteOnShutdown(true);
  27. return bean;
  28. }
  29. }
  30. @H_404_13@

pom.xml中:

  1. 404_13@

在1.2.3下,start方法中的日志语句将它们显示为在线程myTaskExecutor-1中运行.在1.3.3下,相同的日志显示它们在主线程中运行.

知道这里可能有什么问题吗?

最佳答案
您需要将bean工厂方法放在另一个注释为@Configuration的类中. Executor将以这种方式用于@Async方法执行.

  1. @Configuration
  2. @EnableAsync
  3. public class AsyncConfig {
  4. @Bean(name = "myTaskExecutor")
  5. public ThreadPoolTaskExecutor myTaskExecutor() {
  6. return new ThreadPoolTaskExecutor();
  7. }
  8. }
  9. @H_404_13@

猜你在找的Spring相关文章