Search code examples
springspring-bootspring-aop

Pass a string from an aspect to the JointPoint


I have an aspect that executes for each methods in all the Controller classes. My aspect generates a UUID and i wanted to get this ID in my controller, so that i pass it to my service-layer and further process. I am not sure how to pass the UUID from an aspect to the Controller

Below is the aspect

@Configuration
@Aspect
public class ApplicationAspect {



    @Before("execution(* com.spike.aop.arun.*Controller.*(..))")
    public void aspectForAllControllers() {
        System.out.println("Correlation ID generated");
        var correlationId = generateCorrelationId(); // need to pass this to controller

    }

    private String generateCorrelationId() {
        return UUID.randomUUID().toString();
    }
}

Solution

  • One way to achieve this is using RequestContextHolder and set the generated UUID as a request attribute.

    Following code demonstrates the same

    @Before("execution(* com.spike.aop.arun.*Controller.*(..))")
    public void aspectForAllControllers() {
        System.out.println("Correlation ID generated");
        String correlationId = generateCorrelationId(); 
        RequestContextHolder.getRequestAttributes().setAttribute("UUID", correlationId, RequestAttributes.SCOPE_REQUEST);
    
    }
    

    and access the request attribute in the controller.

    @GetMapping("/testUUID")
    public void testUUID(HttpServletRequest request) {
        System.out.println("From Controller :"+request.getAttribute("UUID"));
    }
    

    or

    RequestContextHolder.getRequestAttributes().getAttribute("UUID",RequestAttributes.SCOPE_REQUEST);