2013-02-11 79 views
1

是否有可能在方法结束时执行一个动作,换言之,当函数控件使用注释返回给调用者(或者是因为异常还是正常返回)时?使用注释退出方法时可以执行操作吗?

例子:

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

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

您是否正在使用像Spring或Guice这样的依赖注入框架?它们提供简单的AOP功能。 – 2013-02-11 21:18:33

+0

@ CodyA.Ray感谢您的回复。是的,我正在使用Spring。我不知道AOP,所以我会用它。 – Sumit 2013-02-11 21:55:47

回答

1

你的问题被标记为Spring-Annotations,所以你显然使用Spring。有几个步骤,你想要做什么用Spring:

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

<aop:aspectj-autoproxy/> 

写一个看点(CF Spring AOP vs AspectJ)使用@After@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用作依赖项,那么您还可以将方面应用于未通过接口公开的方法。
0

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

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

相关问题