badera
badera

Reputation: 1545

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?

Upvotes: 5

Views: 9092

Answers (3)

mad_fox
mad_fox

Reputation: 3188

Change your @Around to:

@Aspect
@Component
public class DumpToFileAspect {

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

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

    ...

    return proceed;
  }
}

Upvotes: 2

shakhawat
shakhawat

Reputation: 2727

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

Upvotes: 14

user10639668
user10639668

Reputation:

You can use this:

 @Around("@annotation(dumpFile)")
  public Object logExecutionTime(ProceedingJoinPoint joinPoint,DumpToFile dumpFile) 

Inside the @annotation must be the DumpToFile parameter name.

See the documentation for details

Upvotes: 0

Related Questions