是否可以在方法结束时执行操作,换句话说,当函数控件使用注释返回调用者时(由于异常或正常返回)?
示例:
@DoTaskAtMethodReturn
public void foo() {
.
.
.
Method foo Tasks
.
.
.
return; --------> Background task done by annotation hook here before returning to caller.
}
答案 0 :(得分:1)
您的问题标有 Spring-Annotations ,因此您显然使用的是Spring。使用Spring可以执行以下几个步骤:
您的配置中<aop:aspectj-autoproxy/>
撰写使用@After
和Spring 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
}
}
请注意以下限制:
答案 1 :(得分:0)
是的,但不仅仅是注释。
您必须编写自己的注释处理器并使用代码注入。
How to write a Java annotation processor?
答案 2 :(得分:0)
简短的回答是“是的,这是可能的”。这是所谓的面向方面编程(AOP)的一部分。基于注释的AOP的常见用法是@Transactional,用于包装事务中的所有数据库活动。
你如何处理这取决于你正在构建什么,你正在使用什么(如果有)框架等。如果你使用Spring进行依赖注入,这个SO answer有一个很好的例子或者你可以查看Spring docs。另一个选择是使用Guice(我的偏好),它允许easy AOP。