Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass value to custom annotation in java?

Tags:

java

spring

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?

like image 790
Danni Chen Avatar asked Sep 15 '17 09:09

Danni Chen


People also ask

What is @target annotation in Java?

If an @Target meta-annotation is present, the compiler will enforce the usage restrictions indicated by ElementType enum constants, in line with JLS 9.7. 4. For example, this @Target meta-annotation indicates that the declared type is itself a meta-annotation type.

What is @interface annotation in Java?

Annotation is defined like a ordinary Java interface, but with an '@' preceding the interface keyword (i.e., @interface ). You can declare methods inside an annotation definition (just like declaring abstract method inside an interface). These methods are called elements instead.

How do you pass value to custom annotations?

Annotations require constant values and a method parameter is dynamic. Show activity on this post. Annotation Usage: @CacheClear(pathToVersionId = "[0]") public int importByVersionId(Long versionTo){ ...... }


2 Answers

That's not possible.

Annotations require constant values and a method parameter is dynamic.

like image 146
Luciano van der Veekens Avatar answered Oct 12 '22 01:10

Luciano van der Veekens


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.

like image 37
Sahil Chhabra Avatar answered Oct 12 '22 00:10

Sahil Chhabra