简体   繁体   English

在异步方法上使用Spring AOP

[英]Use of Spring AOP on Async method

Is it possible to use @After and @Around with a @Async method? 是否可以将@After和@Async@Async方法一起使用?
I tried with both of the annotation like this: 我尝试了两个注释,如下所示:

@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

The after part is called before the method end. 在方法结束之前调用after部分。 I tried also with the @After and @Before annotation and the result is the same. 我也尝试了@After@Before注释,结果是相同的。

Do you know if it is possible? 你知道有可能吗?

@After will not work correctly with @Async as the work has not completed yet. @After无法与@Async一起正常使用,因为该工作尚未完成。 You can solve this by returning a CompletableFuture instead of void for your async method and handling any after logic with a callback method. 您可以通过为您的异步方法返回CompletableFuture而不是void并使用回调方法处理任何after逻辑来解决此问题。 Without testing here is an example: 一个未经测试的示例:

    @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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM