Using annotations element-value pairs in AspectJ


This post is part of an series of posts about AspectJ and AOP.

Annotations with element-value pairs

Annotations by themselves are really powerful. They give direct control over when an aspect should be run to the developer. Adding element-value pairs makes the already powerful annotations even more powerful, since it enables you to pass information into the aspect.


Creating an annotation with an element-value pair is in itself quite simple. It can take different parameters and it’s up to the aspect developer to use these in their aspects. The syntax is  @annotation(elementValuePairs) and the elementValuePairs is defined by [keyName] = [value]. If you want more than one elementValuePairs  you use the ,  as a delimiter.

You can get the code for this blog series at the Git repository here.

Let’s start coding!

Requirements: Maven, Java 8, (preferably) an IDE (I’m using IntelliJ)

Adding a element-value pair is quite simple. Getting access to it from the aspect and advice body is a little bit tricky. Let’s start with a example.

The @Retention  and @Target  define the scope of the annotation and you can add multiple @Target  values. We have a boolean with the name isRun() with a default value of true . So let’s continue and access the isRun()  from the aspect.

We specify that the  annotationPointCutDefinition(YourAnnotation yourAnnotationVariableName) contains a YourAnnotation reference. The variable reference is then used in the @Pointcut("@annotation(yourAnnotationVariableName")  instead of the generic YourAnnotation that were used in the earlier examples. By passing the variable to the @annotation we gain access to it. We need to pass the variable into the @Around  advice to gain access to the variable in the advice body.  Once in the advice body we can use it like a normal method parameter.

We add the annotation to our methods and have the option to omit the parameter or directly specify the value of the parameter. If the parameter is omitted the parameter will get it’s default value specified in the annotation.


Annotations with element-value pairs can be really powerful for both the developer who is using the aspects and as the one developing them. It gives the ability to send parameters into the aspect code. By adding the ability to send parameters we open up the code to be more configurable. By having aspects that are configurable we open up the code to be separated into it’s own independent framework or library.

You can get the code for this blog series at the Git repository here.


This post is part of an series of posts about AspectJ and AOP.

This Post Has 4 Comments

  1. Very good leason!
    I got ,thanks!
    I like the annotaion merge aspectj!

  2. Great article,
    Thanks allot

  3. Can i pass the parameter arguments dynamically?
    @YourAnnotation(isRun = parameter.getBoolean)

Leave a Reply

Close Menu