java - 如何解决 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),但它没用,那怎么了?如何解决?
解决方案
请使用以下方法,它可能会帮助您解决此问题。
@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());
}
}
推荐阅读
- javascript - 为什么在 React.js 中为组件使用单独的 CSS 文件
- python - 如何将热图和等高线图与 Plotly Python 相结合
- r - 在行中重复时更改单元格的值 - R
- java - 如何检查系统托盘是否已经存在?
- html - 使用 css 更改 svg 文本定位
- android - 在房间数据库中插入值
- java - 我想从网络下载图像但给出这个异常:android.system.ErrnoException:打开失败:ENOENT(没有这样的文件或目录)
- python - 在 Python 中从元组列表(来自 sqlalchemy 的响应)中划分和追加到两个变量的最快方法是什么?
- html - table td row 重叠在表头上
- python - scipy.stats.pearsonr 抱怨操作数类型 -: 'tuple' 和 'float'