Search code examples
javaannotationsspring-annotations

Is it possible to Perform an action when the method exits using an annotation?


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.
}

Solution

  • 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:

    • Unless you enable AspectJ compile-time weaving or use a javaagent parameter, the object containing foo must be created via Spring, i.e. you must retrieve it from the application context.
    • Without additional dependencies, you can only apply aspects on methods that are declared through interfaces, i.e. foo() must be part of an interface. If you use cglib as an dependency, then you can also apply aspects on methods that are not exposed though an interface.