how to get the object returned from joinPoint.proceed() with Spring AOP and WebFlux

泪湿孤枕 提交于 2019-12-12 01:16:50

问题


I have a simple aspect (see below) with @Around annotation. This aspect works when the the application don't use reactive paradigm. But when the application returns Mono or Flux doesn't works properly.

I need to get the object returned from the method to generate a JSON object to use as log, generate events, etc.

Here is my code that works in a non reactive classes:

@Around("@annotation(simpleEvent)")
public Object logExecutionTime(ProceedingJoinPoint joinPoint, SimpleEvent simpleEvent) throws Throwable {
    final long start = System.currentTimeMillis();
    Object proceed = null;
    try {
        proceed = joinPoint.proceed();
        // here in the real life the object that transformed in json to do others actions
        System.out.println(proceed);
        final long executionTime = System.currentTimeMillis() - start;
        System.out.println(joinPoint.getSignature() + " executed in " + executionTime + "ms");
        return proceed;
    } catch (Exception e) {
        e.printStackTrace(); 
    }
    return proceed;
}

How to get the object returned from joinPoint.proceed() when is Mono or Flux?

Thanks in advance.


回答1:


you can do like this, same when proceed return a Mono

@Around("somePointCut()")
public Object aspectForSomething(ProceedingJoinPoint point) throws Throwable {
    Flux flux = (Flux) point.proceed();
    return flux
            .doOnNext(obj -> {
                log.error("just take a look: " + obj);
            })
            .map(obj -> {
                if (obj instanceof SomeBo) {
                    SomeBo bo = (SomeBo) obj;
                    bo.setName("do some modification");
                    return bo;
                } else {
                    return obj;
                }
            });
}



回答2:


The key is to wrap the joinPoint.proceed() in Mono and access it in a reactive chain.

@Around("@annotation(simpleEvent)")
public Object logExecutionTime(ProceedingJoinPoint joinPoint, SimpleEvent simpleEvent) throws Throwable {
    final long start = System.currentTimeMillis();
    Mono proceed = null;
    try {
        proceed = (Mono) joinPoint.proceed();

        return proceed.doOnNext(response -> {
            final long executionTime = System.currentTimeMillis() - start;
            // here you can access the response object and do your actions
            System.out.println(response);
            System.out.println(joinPoint.getSignature() + " executed in " + executionTime + "ms");
        });
    } catch (Exception e) {
        e.printStackTrace();
    }
    return proceed;
}


来源:https://stackoverflow.com/questions/53137150/how-to-get-the-object-returned-from-joinpoint-proceed-with-spring-aop-and-webf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!