是否可以使用@After和@Around与@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并使用回调方法处理任何后逻辑来解决此问题。没有测试这里是一个例子:
@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";
});
}