【问题标题】:how to resolve Spring boot @EnableAsync and @Async problem?如何解决 Spring boot @EnableAsync 和 @Async 问题?
【发布时间】:2019-03-29 13:39:18
【问题描述】:

我的服务:

@Service
public class ForgetService{
   @Async
   public CompletableFuture<Object> getTokenService() {
       Map<String, Object> map = new HashMap<>(8);
       map.put("status", ErrorEnum.TOKEN_SUSSCESS.getStatus());
       map.put("message", ErrorEnum.TOKEN_SUSSCESS.getMessage());
       return CompletableFuture.completedFuture(map); 
   }
}

我的控制器:

@RestController
public class ForgetController {
   private final ForgetService forgetService;
   @Autowired
   private ForgetController(ForgetService forgetService) {
       this.forgetService = forgetService;
   }
   @PostMapping(value = "/forget/token")
   @Async
   public CompletableFuture<Object> getTokenController() {
       return CompletableFuture.completedFuture(forgetService.getTokenService());
}

}

spring boot 应用类:

@SpringBootApplication
@EnableAsync
public class ApitestApplication {
   public static void main(String[] args) {
       SpringApplication.run(ApitestApplication.class, args);
   }
}

当我运行我的应用程序时,控制台日志:

bean 'forgetService' 不能作为 'com.apitest.service.ForgetService' 注入,因为它是一个 JDK 动态代理,它实现: com.apitest.inf.ForgetServiceInf

行动:

考虑将 bean 作为其接口之一注入或通过在 @EnableAsync 和/或 @EnableCaching 上设置 proxyTargetClass=true 来强制使用基于 CGLib 的代理。


我尝试在 application.properties 中设置 'spring.aop.proxy-target-class=true' 并设置 '@EnableAsync(proxyTargetClass=true),但它没有用,那怎么了?如何解决?

【问题讨论】:

  • 为什么需要两层的@Async?从控制器或服务中删除异步。

标签: java spring spring-boot


【解决方案1】:

请使用以下方法,它可能会帮助您解决此问题。

@Service
public class ForgetService{
   @Bean("GetTokenService")
   public CompletableFuture<Object> getTokenService() {
       Map<String, Object> map = new HashMap<>(8);
       map.put("status", ErrorEnum.TOKEN_SUSSCESS.getStatus());
       map.put("message", ErrorEnum.TOKEN_SUSSCESS.getMessage());
       return CompletableFuture.completedFuture(map); 
   }
@RestController
public class ForgetController {
   private final ForgetService forgetService;
   @Autowired
   private ForgetController(ForgetService forgetService) {
       this.forgetService = forgetService;
   }
   @PostMapping(value = "/forget/token")
   @Async("GetTokenService")
   public CompletableFuture<Object> getTokenController() {
       return CompletableFuture.completedFuture(forgetService.getTokenService());
}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-16
    • 2021-11-14
    • 2020-01-06
    • 2017-10-19
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    • 2020-04-05
    相关资源
    最近更新 更多