Stéphane GRILLON
Stéphane GRILLON

Reputation: 11864

How to get parameter of custom annotation by aspect?

In my aspect method, i need get value of name (param of custom annotation) name = "unit test"

Method call by user:

@Service
@RequiredArgsConstructor
@Slf4j
public class Task {

    @CronLogger(name = "unit test")
    public void testCronLogger(String param) {
        log.info("testCronLogger ...");
    }

}

custom annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CronLogger {
   public String name() default "";
}

Aspect method:

@Aspect
@Component
@EnableAspectJAutoProxy
public class CronLoggerAspect {
    
    private static final Logger log = LoggerFactory.getLogger(CronLoggerAspect.class);
    
    @Around("@annotation(CronLogger)")
    public Object trace(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] tab = joinPoint.getArgs();
        for (Object object : tab) {
            log.debug("CronLogger: {}", object);
        }
       return joinPoint.proceed();
    }
}

Console:

CronLogger: test
testCronLogger ...

Upvotes: 0

Views: 2302

Answers (2)

kriegaex
kriegaex

Reputation: 67297

How about this (untested, I simply modified your code)?

@Around("@annotation(cronLogger)")
public Object trace(ProceedingJoinPoint joinPoint, CronLogger cronLogger) throws Throwable {
  log.debug("CronLogger: {}", cronLogger.name());
  return joinPoint.proceed();
}

Please be careful with upper- and lower-case characters. One is an annotation class name, the other a method parameter name.

Upvotes: 1

Stéphane GRILLON
Stéphane GRILLON

Reputation: 11864

need get Method and get Annotation of this method.

@Around("@annotation(CronLogger)")
public Object trace(ProceedingJoinPoint joinPoint) throws Throwable {
    String name = MethodSignature.class.cast(joinPoint.getSignature()).getMethod().getAnnotation(CronLogger.class)
            .name();
    log.debug("CronLogger: {}", name);
    return joinPoint.proceed();
}

Upvotes: 1

Related Questions