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:

  1. Define a custom annotation

  2. Apply it to the method we want to protect

  3. Create an Aspect that intercepts the method and performs authorization

  4. 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 @Before to intercept method execution.

  • HttpServletRequest is 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

  1. Use a custom annotation to mark methods where events should be triggered.

  2. Write an aspect using @AfterReturning to intercept only successful executions.

  3. Inject the HttpServletRequest and access the returned object (response).

  4. 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