简体   繁体   中英

How to pass value to custom annotation in java?

my custom annotation is:

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

    long versionId() default 0;
}

I want to achieve something like this, in which I can pass the method param "versionTo" to my custom annotation.

@CacheClear(versionId = {versionTo})
public int importByVersionId(Long versionTo){
    ......
} 

What should I do?

That's not possible.

Annotations require constant values and a method parameter is dynamic.

You cannot pass the value, but you can pass the path of that variable in Spring Expression and use AOP's JoinPoint and Reflection to get and use it. Refer below:

Your Annotation:

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

    String pathToVersionId() default 0;
}

Annotation Usage:

@CacheClear(pathToVersionId = "[0]")
public int importByVersionId(Long versionTo){
    ......
} 

Aspect Class:

@Component
@Aspect
public class YourAspect {

   @Before ("@annotation(cacheClear)")
   public void preAuthorize(JoinPoint joinPoint, CacheClear cacheClear) {
      Object[] args = joinPoint.getArgs();
      ExpressionParser elParser = new SpelExpressionParser();
      Expression expression = elParser.parseExpression(cacheClear.pathToVersionId());
      Long versionId = (Long) expression.getValue(args);

      // Do whatever you want to do with versionId      

    }
}

Hope this helps someone who wants to do something similar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM