【问题标题】:Is it possible to Perform an action when the method exits using an annotation?当方法使用注释退出时是否可以执行操作?
【发布时间】:2013-02-11 21:10:45
【问题描述】:

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

例子:

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

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

【问题讨论】:

  • 你在使用像 Spring 或 Guice 这样的依赖注入框架吗?它们提供简单的 AOP 功能。
  • @CodyA.Ray 感谢您的回复。是的,我正在使用 Spring。我不了解 AOP,所以我将使用它。

标签: java annotations spring-annotations


【解决方案1】:

您的问题带有 Spring-Annotations 标记,因此您显然使用的是 Spring。有几个步骤可以用 Spring 做你想做的事:

Enable AspectJ/AOP-Support 在您的配置中:

<aop:aspectj-autoproxy/>

编写一个使用@After@annotation pointcut 的方面(c.f. Spring AOP vs AspectJ):

@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 作为依赖项,那么您还可以将方面应用于未通过接口公开的方法。

【讨论】:

    【解决方案2】:

    是的,但不仅仅是注释。

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

    How to write a Java annotation processor?

    What is Java bytecode injection?

    Java byte-code injection

    【讨论】:

    • 您不必使用字节码注入。各种 AOP 框架都允许这种行为。
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-28
      • 2016-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-10
      • 1970-01-01
      • 2011-07-02
      相关资源
      最近更新 更多