[英]Use of Spring AOP on Async method
是否可以将@After和@Async
与@Async
方法一起使用?
我尝试了两个注释,如下所示:
@Override
@SetUnsetEditingFleet
public void modifyFleet(User user, FleetForm fleetForm) throws Exception{
databaseFleetsAndCarsServices.modifyFleet(user, fleetForm);
}
@Around("@annotation(SetUnsetEditingFleet) && args(user, fleetForm)")
public void logStartAndEnd(ProceedingJoinPoint pjp, User user, FleetForm fleetForm) throws Throwable{
fleetServices.setEditingFleet(fleetForm.getIdFleet());
for(Car car : carServices.findByFleetIdFleet(fleetForm.getIdFleet())){
carServices.setEditingCar(car.getIdCar()); //Set cars associated with the fleet
}
pjp.proceed();
fleetServices.unSetEditingFleet(fleetForm.getIdFleet());
for(Car car : carServices.findByFleetIdFleet(fleetForm.getIdFleet())){
carServices.unSetEditingCar(car.getIdCar()); //Unset cars associated with the fleet
}
}
@Override
@Async
@Transactional(rollbackFor=Exception.class)
public void modifyFleet(User currentUser, FleetForm fleetForm) throws Exception {
//method instructions
在方法结束之前调用after部分。 我也尝试了@After
和@Before
注释,结果是相同的。
你知道有可能吗?
@After无法与@Async一起正常使用,因为该工作尚未完成。 您可以通过为您的异步方法返回CompletableFuture而不是void并使用回调方法处理任何after逻辑来解决此问题。 一个未经测试的示例:
@Around("@annotation(AsyncBeforeAfter)")
public void asyncBeforeAfter(ProceedingJoinPoint pjp) throws Throwable{
// before work
Object output = pjp.proceed();
CompletableFuture future = (CompletableFuture) output;
future.thenAccept(o -> {
// after work
});
}
@Override
@Async
@AsyncBeforeAfter
@Transactional(rollbackFor=Exception.class)
public CompletableFuture<String> modifyFleet(User currentUser, FleetForm fleetForm) throws Exception {
return CompletableFuture.supplyAsync(() -> {
//method instructions
return "done";
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.