如何使用Spring AOP和WebFlux从joinPoint.proceed()返回对象

问题描述 投票:0回答:1

我有一个简单的方面(见下文)与@Around注释。当应用程序不使用反应范例时,此方面有效。但是当应用程序返回Mono或Flux无法正常工作时。

我需要从方法返回的对象生成一个JSON对象,用作日志,生成事件等。

这是我的代码在非反应类中工作:

@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;
}

当Mono或Flux时,如何从joinPoint.proceed()返回对象?

提前致谢。

java spring spring-aop spring-webflux project-reactor
1个回答
0
投票

你可以这样做,同样继续返回单声道

@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;
                }
            });
}
© www.soinside.com 2019 - 2024. All rights reserved.