spring-aop/spring-aop-advice-afterReturningAdvice/README.md
✒️ 作者 - Lex 📝 博客 - 掘金 📚 源码地址 - github
AfterReturningAdvice接口是Spring AOP框架中的一个核心接口,用于在目标方法执行后拦截并执行自定义逻辑。通过实现该接口的afterReturning方法,可以在目标方法成功返回结果后进行一些操作。
日志记录
性能监控
缓存处理
统一处理
AfterReturningAdvice接口主要用于在方法正常返回时执行后置通知。后置通知可以查看方法的返回值,但不能修改它,并且仅在方法正常返回时被调用,不会在抛出异常时被调用。该接口提供了一个afterReturning方法,在方法成功返回后进行回调,其中包含了返回值、被调用的方法、方法的参数以及方法调用的目标对象等信息。
/**
* 后置返回通知仅在方法正常返回时被调用,如果抛出异常则不会被调用。这样的通知可以查看方法的返回值,但不能修改它。
*
* 作者:Rod Johnson
* @see MethodBeforeAdvice
* @see ThrowsAdvice
*/
public interface AfterReturningAdvice extends AfterAdvice {
/**
* 在给定方法成功返回后的回调。
* @param returnValue 方法返回的值,如果有的话
* @param method 被调用的方法
* @param args 方法的参数
* @param target 方法调用的目标对象。可能为{@code null}。
* @throws Throwable 如果此对象希望中止调用。如果方法签名允许,将返回任何抛出的异常给调用者。否则,异常将被包装为运行时异常。
*/
void afterReturning(@Nullable Object returnValue, Method method, Object[] args, @Nullable Object target) throws Throwable;
}
AspectJAfterReturningAdvice
classDiagram
direction BT
class Advice {
<<Interface>>
}
class AfterAdvice {
<<Interface>>
}
class AfterReturningAdvice {
<<Interface>>
}
class AspectJAfterReturningAdvice
AfterAdvice --> Advice
AfterReturningAdvice --> AfterAdvice
AspectJAfterReturningAdvice ..> Advice
AspectJAfterReturningAdvice ..> AfterAdvice
AspectJAfterReturningAdvice ..> AfterReturningAdvice
使用Spring AOP中的后置返回通知(AfterReturningAdvice)。首先,创建了一个代理工厂(ProxyFactory)并指定目标对象(MyService)。然后,创建了一个后置返回通知(MyAfterReturningAdvice)并添加到代理工厂中。接着,通过代理工厂获取代理对象,并调用代理对象的方法。
public class AfterReturningAdviceDemo {
public static void main(String[] args) {
// 创建代理工厂&创建目标对象
ProxyFactory proxyFactory = new ProxyFactory(new MyService());
// 创建通知
proxyFactory.addAdvice(new MyAfterReturningAdvice());
// 获取代理对象
MyService proxy = (MyService) proxyFactory.getProxy();
// 调用代理对象的方法
proxy.foo();
}
}
MyAfterReturningAdvice的类,它实现了Spring AOP框架中的AfterReturningAdvice接口。在afterReturning方法中,当目标方法成功返回结果时,它将打印出目标方法的名称以及返回的值。
public class MyAfterReturningAdvice implements AfterReturningAdvice {
@Override
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("After Method " + method.getName());
}
}
MyService 类是一个简单的服务类,其中包含了一个名为 foo() 的方法。在上下文中,MyService 类被用作目标对象,即需要被拦截和增强的对象。
public class MyService {
public void foo() {
System.out.println("foo...");
}
}
运行结果,成功地执行了代理对象的foo()方法,并在方法执行完成后,后置返回通知MyAfterReturningAdvice被触发。
foo...
After Method foo