Search code examples
javaaop

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

Solution

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