Java SpringAOP在异步方法上的使用

Java SpringAOP在异步方法上的使用,java,spring,asynchronous,annotations,spring-aop,Java,Spring,Asynchronous,Annotations,Spring Aop,是否可以将@After和@Around与@Async方法一起使用? 我尝试了两种注释,如下所示: @Override @SetUnsetEditingFleet public void modifyFleet(User user, FleetForm fleetForm) throws Exception{ databaseFleetsAndCarsServices.modifyFleet(user, fleetForm); } @Around("@annotation(SetUnse

是否可以将@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,并使用回调方法处理任何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";
     });
    }

该方法已结束,因为处理已分派到新线程。因此,对于调用代码,方法执行结束。因此,是的,您可以使用它,但不是您想要使用它的目的。因此,只有@Before可以使用,@After部分在新线程开始后调用,而不是在它结束时调用。是否正确?否在方法末尾调用它。。线程一开始,方法就结束。对于调用代码,方法执行结束。