In Spring Boot and Java have many in built in annotations. Annotations in Java are a form of metadata that provide data about a program but are not part of the program itself. They have no direct effect on the operation of the code they annotate. We can create custom annotations by extending current one or build a new one from scratch.
How to create annotation
Use below syntax to define a custom annotation in Java.
public @interface <AnnotationName>{
}
Here’s a breakdown of the syntax:
- public: This is an access modifier indicating that the annotation can be used by any class.
- @interface: This keyword is used to declare a custom annotation. It is similar to class or interface but specifically for annotations.
- AnnotationName: This is the name of the custom annotation
Adding Meta-Annotations
When creating custom annotations, we typically use meta-annotations to define the behavior and applicability of our custom annotation. Some important meta-annotations are:
@Target
: Specifies where the annotation can be applied (methods, fields, classes, etc.).@Retention
: Defines how long annotations are retained (source code, class file, or runtime).@Documented
: Indicates that elements using this annotation should be documented by JavaDoc.@Inherited
: Indicates that the annotation can be inherited by subclasses.
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@PreAuthorize("hasRole('ROLE_CORE_USER')")
public @interface IsCoreUser {
}
Using the Custom Annotation
Once you have defined your custom annotation, you can use it in your Spring Boot application.
@RestController
public class UserController {
@IsCoreUser
@GetMapping("/user/{id}")
public String getUserById(Long id) {
return service.getUserById(id);
}
}
Benefits of Reusable Annotations
- Code Reusability: Encapsulate common behavior across multiple classes and methods.
- Readability: Annotations provide a clean, declarative style.
- Maintainability: Easy to update and manage behaviors.
- Separation of Concerns: Cleanly separate business logic from cross-cutting concerns.
Conclusion
Creating reusable annotations in Spring Boot enhances modularity and code clarity. They allow developers to abstract recurring patterns, enabling a clean and maintainable architecture. Whether for logging, validation, or security, custom annotations can play a critical role in writing elegant Spring Boot applications.