首页 > 解决方案 > 如何解决 Spring boot @EnableAsync 和 @Async 问题?

问题描述

我的服务:

@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());
}

}

春季启动应用程序类:

@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),但它没用,那怎么了?如何解决?

标签: javaspringspring-boot

解决方案


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

@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());
}

}


推荐阅读