java - 如何解决Spring boot @EnableAsync和@Async问题?

标签 java spring spring-boot

我的服务:

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

我的 Controller :

@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”注入(inject),因为它是实现以下功能的 JDK 动态代理: com.apitest.inf.ForgetServiceInf

行动:

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

<小时/>

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

最佳答案

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

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

}

关于java - 如何解决Spring boot @EnableAsync和@Async问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52980853/

相关文章:

spring-boot - 如何在 Visual Studio 代码中运行 Spring Boot 应用程序?有可能吗?

java - 将无状态 session bean 注入(inject) Seam 2.2 中的 EntityHome 派生后引发空指针异常

java - Spring 框架的验证无法与 JSR-303 验证一起使用

java - 如何在 Java 中分析 String 以判断它是一个单词还是完全乱码?

java - 具有 Java 配置的 Spring Boot 自定义身份验证提供程序不起作用

java - Spring 启动 : Struggling with validating nested entity - where i need to validate only 1 unique property

spring - 为什么 spring boot 将 Expires header 设置为 Expires :?

java - 如何在 java 中为 Neo4j 节点设置节点的属性

具有多个 JVM 的多个实例的 App 中的 Spring Scheduler 代码

java - Spring .andExpect() MockMvc 逻辑 ||相等的