3 quick steps to create custom annotations in Spring Boot
Annotation is a way for adding metadata information to our source code. Sometimes, there is need to create custom annotation in java frameworks depending on requirement. This blog provides you a simple set of steps for quick creation.
Let’s start it with the understanding of 3 annotations to achieve this!
1) @Retention:
This annotation basically tells the compiler for how long we need the annotated type to be remained. Below are the 3 available values for it:
As the name suggests, annotation with retention policy SOURCE will be retained only with source code, and discarded during compile time. Annotation with retention policy CLASS will be retained till compiling the code, and discarded during runtime, while with retention policy RUNTIME will be available to the JVM through runtime. The default retention policy type is CLASS.
2) @Target:
This specifies at what level we want to have our annotation. It could be class level, method level and so on as shown below:
We can specify more than 1 Element Type for a single annotation like below:
3)@interface
@interface is basically used to create the custom annotation. So, it defines the annotation name which will be used with its attributes.
Now, we can just implement the custom annotation like any built-in java annotation as shown below:
Conclusion:
Java annotation is an amazing way to create additional data for programmers, libraries or third party APIs. But, we need to take care of extra overhead of compilation and lookup of annotation in runtime.
Hope you like it.
If you have any related queries, please feel free to contact me. I’ll be happy to help you. Stay Connected :)