gpt4 book ai didi

java - @Around 建议在 Spring AOP 中究竟是如何工作的?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:27:30 25 4
gpt4 key购买 nike

我正在研究 Spring AOP 模块,我对 AROUND 建议的具体工作原理有一些疑问。

阅读官方文档:http://docs.spring.io/spring/docs/current/spring-framework-reference/html/aop.html

我可以阅读有关AROUND ADVICE的内容:

Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception.

这是环绕通知的序列图:

enter image description here

因此,据我所知,我可以定义一个建议(我的自定义行为),该建议将在切入点指定的关节点之前和之后执行。

例如,我可以这样定义一个AROUND ADVICE:

@Around(“execution(@example.Cacheable * rewards.service..*.*(..))”)
public Object cache(ProceedingJoinPoint point) throws Throwable {
Object value = cacheStore.get(cacheKey(point));

if (value == null) {
value = point.proceed();
cacheStore.put(cacheKey(point), value);
}
return value;
}

在调用服务方法之前和之后执行已实现的缓存行为。对吗?

我无法完全理解的是 ProceedingJoinPoint 点 参数究竟是如何使用的以及它是如何使用的。

据我了解,它用于选择是否执行特定操作,但具体是如何工作的?

关于如何正确使用 AOP 建议的另一个疑问是如何回答以下问题:

Which advice do I have to use if I would like to try and catch exceptions?

我认为在这种情况下,答案是使用After throw advice,因为当匹配的方法执行通过抛出异常退出时,该建议就会执行。

但我不确定,因为据我了解,建议仅在方法抛出异常时执行。或者在这种情况下我必须使用 **AROUND ADVICE* ?

谢谢

最佳答案

实际上,所有这些 AOP 注释都作为 AbstractAspectJAdvice 的具体实现公开。即使它是 @AfterThrowing,它的 AspectJAfterThrowingAdvice 仍然存在并被调用:

try {
return mi.proceed();
}
catch (Throwable t) {
if (shouldInvokeOnThrowing(t)) {
invokeAdviceMethod(getJoinPointMatch(), null, t);
}
throw t;
}

@Around 确实拥有更强大的功能,并为最终用户提供更多控制权来处理 ProceedingJoinPoint

要研究所有这些建议类型,但是使用 @Around 你可以接触到所有这些,尽管你不应该忘记调用 mi.proceed() 从那里。当然,如果需要按照您的逻辑执行此操作。

关于java - @Around 建议在 Spring AOP 中究竟是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29193489/

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