是否可以在方法末尾执行操作,换句话说,当函数控制返回到调用者时(由于异常或正常返回)使用注释?
示例:
@DoTaskAtMethodReturn
public void foo() {
.
.
.
Method foo Tasks
.
.
.
return; --------> Background task done by annotation hook here before returning to caller.
}
最佳答案
你的问题被标记为Spring-Annotations,所以你显然正在使用Spring。使用 Spring 执行您想要的操作有几个步骤:
Enable AspectJ/AOP-Support在您的配置中:
<aop:aspectj-autoproxy/>
编写一个使用 @After
和 Spring AOP vs AspectJ 的方面(参见 @annotation
pointcut ) :
@Aspect
public class TaskDoer {
@After("@annotation(doTaskAnnotation)")
// or @AfterReturning or @AfterThrowing
public void doSomething(DoTaskAtMethodReturn doTaskAnnotation) throws Throwable {
// do what you want to do
// if you want access to the source, then add a
// parameter ProceedingJoinPoint as the first parameter
}
}
请注意以下限制:
- 除非您启用 AspectJ 编译时编织或使用 javaagent 参数,否则包含 foo 的对象必须通过 Spring 创建,即您必须从应用程序上下文中检索它。
- 如果没有额外的依赖项,您只能将方面应用于通过接口(interface)声明的方法,即 foo() 必须是接口(interface)的一部分。如果您使用 cglib 作为依赖项,那么您还可以对未通过接口(interface)公开的方法应用方面。
关于java - 是否可以使用注释在方法退出时执行操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14820922/