Spring Framework FAQ: Top Questions
33. How do you define custom annotations in Spring?
You can create custom annotations in Spring by defining a Java annotation and configuring a handler or aspect to respond to it.
πΊοΈ Steps:
- Create the annotation using
@interface
. - Use it on classes/methods and process it using AOP or meta-annotations.
π₯ Example:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Auditable {
}
@Aspect
@Component
public class AuditAspect {
@Before("@annotation(Auditable)")
public void audit() {
System.out.println("Audit log recorded");
}
}
π Expected Output:
Method calls with @Auditable are logged before execution.
π οΈ Use Cases:
- Audit trails, performance monitoring.
- Reusability and semantic decoration of business logic.