1

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.
}
Sumit
  • 57
  • 1
  • 6
  • Are you using a Dependency Injection framework like Spring or Guice? They provide simple AOP functionality. – Cody A. Ray Feb 11 '13 at 21:18
  • @CodyA.Ray Thanks for responding. Yes I am using Spring. I didn't know about AOP, so I will use that. – Sumit Feb 11 '13 at 21:55

3 Answers3

1

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.
Community
  • 1
  • 1
nd.
  • 8,699
  • 2
  • 32
  • 42
0

Yes, but not only with annotation.

You have to write your own annotation processor and use code injection.

How to write a Java annotation processor?

What is Java bytecode injection?

Java byte-code injection

Community
  • 1
  • 1
Aubin
  • 14,617
  • 9
  • 61
  • 84
0

The short answer is "Yes, it is possible". This is part of what's called Aspect Oriented Programming (AOP). A common use of annotation-based AOP is @Transactional for wrapping all database activities in a transaction.

How you go about this depends on what you're building, what (if any) frameworks you're using, etc. If you're using Spring for dependency injection, this SO answer has a good example or you can checkout the Spring docs. Another option is to use Guice (my preference), which allows easy AOP.

Community
  • 1
  • 1
Cody A. Ray
  • 5,869
  • 1
  • 37
  • 31