java - 是否可以使用注释在方法退出时执行操作?

标签 java annotations spring-annotations

是否可以在方法末尾执行操作,换句话说,当函数控制返回到调用者时(由于异常或正常返回)使用注释?

示例:

@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/>

编写一个使用 @AfterSpring 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/

相关文章:

java - Spring MVC 随着页面方向的改变而改变语言环境

java - 注解参数: explicit vs.隐式String数组

java - 无法解析 org.springframework.transaction.annotation.Transactional 的依赖关系

java - 如何获取当前选项卡的Jtable或者jTable模型?

java小程序,按钮数组运行时问题

java - 对 MockUp 与 Expectations 的优点感到困惑

java - 在 Spring 中将 @Configuration 与 @ComponentScan 一起使用的具体用例是什么?

java - 在运行期间或之前用日志记录替换 java 注释

java - 在没有 Spring 的情况下注入(inject)应用程序属性

java - 如何指定 AutoWired Bean 的子依赖项