gpt4 book ai didi

java - 如何使用 Spring AOP 和 WebFlux 获取从 joinPoint.proceed() 返回的对象

转载 作者:行者123 更新时间:2023-12-02 10:38:00 27 4
gpt4 key购买 nike

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

我需要获取从方法返回的对象来生成 JSON 对象以用作日志、生成事件等。

这是我在非响应式(Reactive)类中工作的代码:

@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()返回的对象?

提前致谢。

最佳答案

你可以这样做,当继续返回一个 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;
}
});
}

关于java - 如何使用 Spring AOP 和 WebFlux 获取从 joinPoint.proceed() 返回的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53137150/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com