Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Custom Annotations with AOP and Interceptors in Spring Boot

Tech Nov 12 16

Four Core Meta-Annotations

When creating custom annotations in Java, @Target, @Retention, @Documented, and @Inherited are essential meta-annotations that define how your custom annotation behaves and can be applied.

1. @Target

The @Target annotation specifies which program elements your custom annotation can be applied to. It accepts an array of ElementType anumeration values, including classes, methods, fields, and more. Common ElementType values include:

  • ElementType.TYPE: Classes, interfaces, enums
  • ElementType.METHOD: Methods
  • ElementType.FIELD: Fields
  • ElementType.PARAMETER: Method parameters
  • ElementType.CONSTRUCTOR: Constructors
  • ElementType.LOCAL_VARIABLE: Local variables
  • ElementType.ANNOTATION_TYPE: Annotation types
  • ElementType.PACKAGE: Packages

For example, to restrict an annotation to methods only:

@Target(ElementType.METHOD)

2. @Retention

The @Retention annotation defines how long your custom annotation is retained. It uses the RetentionPolicy enumeration:

  • RetentionPolicy.SOURCE: Annotation is discarded during compilation, only present in source code
  • RetentionPolicy.CLASS: Annotation is stored in the class file but not available at runtime (default)
  • RetentionPolicy.RUNTIME: Annotation is available at runtime and accessible via reflection

To make an annotation accessible during runtime:

@Retention(RetentionPolicy.RUNTIME)

3. @Documented

The @Documented annotation ensures your custom annottaion is included in Javadoc-generated documentation. It has no attributes and is applied directly to the annotation definition:

@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ActionLog {
    // Annotation definition
}

This ensures that any usage of @ActionLog appears in the generated Javadoc.

4. @Inherited

The @Inherited annotation allows a class-level custom annotation to be inherited by subclasses. Note that this only applies to class inheritance, not to interfaces, methods, or fields:

@Inherited
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface ServiceMarker {
    // Annotation definition
}

If a parent class is annotated with @ServiceMarker, all its subclasses will inherit this annotation automatically.

Implementing a Custom Annotation with AOP

1. Create the Custom Annotation

Let’s define a @ActionLog annotation that tracks method operations and details. It targets methods and is retained at runtime:

package com.example.demo.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ActionLog {
    String operation() default "";
    String detail() default "";
}

2. Implement AOP Aspect

Create an aspect class ActionLogAspect that uses @ActionLog as a pointcut. This aspect will log method execution details before, after, and around the target method:

package com.example.demo.aspects;

import com.example.demo.annotations.ActionLog;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Component
public class ActionLogAspect {

    private static final Logger logger = LoggerFactory.getLogger(ActionLogAspect.class);

    @Pointcut("@annotation(actionLog)")
    public void actionLogPointcut(ActionLog actionLog) {}

    @Before("@annotation(actionLog)")
    public void beforeMethodExecution(ActionLog actionLog) {
        System.out.println("Pre-action: " + actionLog.operation() + " - " + actionLog.detail());
    }

    @After("@annotation(actionLog)")
    public void afterMethodExecution(ActionLog actionLog) {
        System.out.println("Post-action: " + actionLog.operation() + " - " + actionLog.detail());
    }

    @Around("@annotation(actionLog)")
    public Object aroundMethodExecution(ProceedingJoinPoint joinPoint, ActionLog actionLog) throws Throwable {
        long start = System.currentTimeMillis();

        Object result = joinPoint.proceed();

        long end = System.currentTimeMillis();
        long executionTime = end - start;

        logger.info("Executed Method: {}", joinPoint.getSignature().getName());
        logger.info("Execution Duration: {}ms", executionTime);
        Object[] parameters = joinPoint.getArgs();
        for (int i = 0; i < parameters.length; i++) {
            logger.info("Parameter {}: {}", i + 1, parameters[i]);
        }
        logger.info("Action Log: {} - {}", actionLog.operation(), actionLog.detail());

        return result;
    }
}

3. Use the Custom Annotation

Apply @ActionLog to a service method to enable logging:

package com.example.demo.services;

import com.example.demo.annotations.ActionLog;
import org.springframework.stereotype.Service;

@Service
public class OrderService {

    @ActionLog(operation = "Process Order", detail = "Handles new order submission")
    public void processNewOrder() {
        System.out.println("Executing order processing logic...");
    }
}

4. Test the Implementation

Write a JUnit test to verify the aspect works correctly:

package com.example.demo;

import com.example.demo.services.OrderService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class AnnotationDemoApplicationTests {

    @Autowired
    OrderService orderService;

    @Test
    void testOrderProcessing() {
        orderService.processNewOrder();
    }
}

Implementing Authentication with Custom Annotation and Interceptor

1. Create the Auth Annotation

Define @AuthRequired to mark methods that require valid authentication:

package com.example.demo.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AuthRequired {
}

2. AOP Aspect for Auth Tracking

Create an aspect to log when @AuthRequired methods are accessed:

package com.example.demo.aspects;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class AuthRequiredAspect {

    private static final Logger logger = LoggerFactory.getLogger(AuthRequiredAspect.class);

    @Before("@annotation(com.example.demo.annotations.AuthRequired)")
    public void beforeAuthMethod() {
        logger.info("Accessing method that requires authentication...");
    }
}

3. Apply the Annotation to a Controller

Use @AuthRequired on a controller endpoint to enforce authentication:

package com.example.demo.controllers;

import com.example.demo.annotations.AuthRequired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @GetMapping("/user/profile")
    @AuthRequired
    public String getUserProfile() {
        return "User Profile Data";
    }
}

4. Configure Interceptor in Main Class

Update the main application class to register the authentication interceptor:

package com.example.demo;

import com.example.demo.interceptors.AuthValidationInterceptor;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@SpringBootApplication
public class AnnotationDemoApplication implements WebMvcConfigurer {

    public static void main(String[] args) {
        SpringApplication.run(AnnotationDemoApplication.class, args);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new AuthValidationInterceptor());
    }
}

5. Implement Authentication Interceptor

Create an interceptor that checks for valid tokens when @AuthRequired is present:

package com.example.demo.interceptors;

import com.example.demo.annotations.AuthRequired;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthValidationInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(AuthValidationInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.debug("Entering interceptor for URL: {}", request.getServletPath());

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;

        if (!handlerMethod.hasMethodAnnotation(AuthRequired.class)) {
            logger.debug("Endpoint does not require authentication, allowing access");
            return true;
        }

        String token = request.getHeader("Authorization");

        if (token != null && token.equals("Bearer SECRET_TOKEN_123")) {
            return true;
        } else {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid or missing authentication token");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, org.springframework.web.servlet.ModelAndView modelAndView) throws Exception {
        // No post-handle logic needed
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // No after-completion logic needed
    }
}
Tags: Spring Boot

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.