Search code examples
javaspringannotationsaopaspectj

annotation with parameter for aspect


I have an aspect usable with an annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface DumpToFile {

}

And the join point:

@Aspect
@Component
public class DumpToFileAspect {

  @Around("@annotation(DumpToFile)")
  public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {

    ...
    // I likte to read out a parameter from the annotation...
    Object proceed = joinPoint.proceed();

    ...

    return proceed;
  }
}

I can use the aspect successfully on a method with @DumpToFile; however, I would like to pass a parameter to the annotation and retrieve it's value inside my aspect.
Eg. @DumpToFile(fileName="mydump"). Can anybody show me how to do that?


Solution

  • You should be able to pass the annotation interface to the interceptor method. I haven't tried myself though.

    Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.METHOD)
    public @interface DumpToFile {
    
          String fileName() default "default value";
    
    }
    

    In DumpToFileAspect -

    @Aspect
    @Component
    public class DumpToFileAspect {
    
      @Around("@annotation(dtf)")
      public Object logExecutionTime(ProceedingJoinPoint joinPoint, DumpToFile dtf) throws Throwable {
    
        ...
        // I likte to read out a parameter from the annotation...
    
        System.out.println(dtf.fileName); // will print "fileName"
    
        Object proceed = joinPoint.proceed();
    
        ...
    
        return proceed;
      }
    }