简体   繁体   English

如何在java中将值传递给自定义注释?

[英]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. 我想实现这样的东西,我可以将方法参数“versionTo”传递给我的自定义注释。

@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. 您无法传递该值,但您可以在Spring Expression传递该变量的路径,并使用AOP的 JoinPointReflection来获取和使用它。 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: Aspect类:

@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. 希望这能帮助想要做类似事情的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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