Is it possible to perform an action at the end of a method, in other words when the function control returns to the caller(either because of exception or normal return) using an annotation ?
Example:
@DoTaskAtMethodReturn
public void foo() {
.
.
.
Method foo Tasks
.
.
.
return; --------> Background task done by annotation hook here before returning to caller.
}
Your question is tagged with Spring-Annotations, so you are obviously using Spring. There are several steps to do what you want with Spring:
Enable AspectJ/AOP-Support in your configuration:
<aop:aspectj-autoproxy/>
Write an Aspect (c.f. Spring AOP vs AspectJ) that uses @After
and the @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
}
}
Please note the following restrictions: