Use Cases
1. Perform Authorization Check with the help of HTTP Request Headers
We want to perform an authorization check without touching the controller logic.
Context
In a typical Spring Boot application, authorization logic is often placed in the controller or service methods. However, this tightly couples business logic with security concerns and violates separation of concerns.
We want to perform authorization checks (e.g., checking if the user has permission to access a resource) without modifying the controller or service layer logic.
Solution
We will:
Define a custom annotation
Apply it to the method we want to protect
Create an Aspect that intercepts the method and performs authorization
Keep the business logic clean and focused
Create the Custom Annotation
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface RequireAuthorization {
String role() default "ADMIN";
}This annotation will mark methods that require a role-based check.
The default required role is "ADMIN" but it's customizable.
Create the Aspect
Notes:
The aspect uses
@Beforeto intercept method execution.HttpServletRequestis injected and used to read headers or parameters.We can extend this to check cookies, JWT claims, or session attributes.
Define Custom Exception
Apply the Annotation on a Controller or Service Method
2. Trigger an Notification Event on Successful Payment Response
We want to trigger an event (e.g., sending a notification) only after a controller method returns successfully, without cluttering the controller logic. Request and Response object should be available while triggering that event to capture some of the details from it.
Approach
Use a custom annotation to mark methods where events should be triggered.
Write an aspect using
@AfterReturningto intercept only successful executions.Inject the
HttpServletRequestand access the returned object (response).Capture necessary data and publish a custom Spring event.
Solution
Custom Annotation
Event Class
Aspect to Intercept and Publish Event
Sample Controller
Event Listener
Last updated