这是主应用程序类:
@EnableAsync(proxyTargetClass = true)
@EnableDiscoveryClient
@SpringBootApplication
public class ProductApplication {
public static void main(final String[] args) {
SpringApplication.run(ProductApplication.class, args);
}
@Bean("threadPoolTaskExecutor")
public TaskExecutor getAsyncExecutor() {
final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(20);
executor.setMaxPoolSize(1000);
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setThreadNamePrefix("Async-");
return executor;
}
}
这是服务类别:
@Component
public class ProductServiceImpl implements ProductService {
@Autowired
ProductRepository productRepository;
@Autowired
private ProductHandler productHandler;
@Async
@Override
public List<String> getAllCategories() {
final List<String> finalList = new ArrayList<>();
return finalList;
}
}
这是 Controller 类:
@RestController
public class ProductResource {
@Autowired
private ProductServiceImpl productServiceImpl;
@GetMapping("/categories")
public ResponseEntity<List<String>> getAllCategories() {
return new ResponseEntity<>(this.productServiceImpl.getAllCategories(), HttpStatus.OK);
}
}
我已使用 @Async
注释了服务实现方法,但收到此错误:
Action:
Consider injecting the bean as one of its interfaces or forcing the use of CGLib-based proxies by setting proxyTargetClass=true on @EnableAsync and/or @EnableCaching.
如果我尝试注释 Controller ,我的获取请求将得到空响应。我已经尝试了所有方法,包括将 proxyTargetClass 设置为 true。
最佳答案
只要你使用 @Async
注解,您必须熟悉使用它时必须遵守的规则:
- 该方法必须是
public
仅 - 不能从同一类中的方法调用(自调用)
- 如果使用返回类型,则必须将其包装在
Future<T>
中, 前任。CompletableFuture<T>
所以你得到:
CompletableFuture<List<String>> categories = this.productServiceImpl.getAllCategories();
进一步的处理是由 Future
的实现驱动的您可以在其中阻止执行或 join
将更多内容合并到一个响应中...
关于java - @Async 在 Spring Boot 应用程序中给我错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61134832/