当方法使用注释退出时,是否可以执行操作?

时间:2013-02-11 21:10:46

标签: java annotations spring-annotations

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

示例:

@DoTaskAtMethodReturn
public void foo() {
.
.
. 
Method foo Tasks  
.
.
.

return;  -------->  Background task done by annotation hook here before returning to caller.
}

3 个答案:

答案 0 :(得分:1)

您的问题标有 Spring-Annotations ,因此您显然使用的是Spring。使用Spring可以执行以下几个步骤:

您的配置中

Enable AspectJ/AOP-Support

<aop:aspectj-autoproxy/>

撰写使用@AfterSpring AOP vs AspectJ的方面(c.f. @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参数,否则必须通过Spring创建包含foo的对象,即必须从应用程序上下文中检索它。
  • 如果没有其他依赖项,则只能对通过接口声明的方法应用方面,即foo()必须是接口的一部分。如果您使用cglib作为依赖项,那么您还可以对未通过接口公开的方法应用方面。

答案 1 :(得分:0)

是的,但不仅仅是注释。

您必须编写自己的注释处理器并使用代码注入。

How to write a Java annotation processor?

What is Java bytecode injection?

Java byte-code injection

答案 2 :(得分:0)

简短的回答是“是的,这是可能的”。这是所谓的面向方面编程(AOP)的一部分。基于注释的AOP的常见用法是@Transactional,用于包装事务中的所有数据库活动。

你如何处理这取决于你正在构建什么,你正在使用什么(如果有)框架等。如果你使用Spring进行依赖注入,这个SO answer有一个很好的例子或者你可以查看Spring docs。另一个选择是使用Guice(我的偏好),它允许easy AOP