Search code examples
springspring-bootaoppointcut

Get specific header parameter using Spring AOP?


I have created Spring Boot REST API where all endpoint will have header parameter "sessionGuid". I would like to print that sessionGuid using AOP.

@Before("PointcutDefinition.controllerLayer()")
  public void beforeAdvice(JoinPoint joinPoint)
  {
    Object[] signatureArgs = joinPoint.getArgs();
    for (Object signatureArg : signatureArgs)
    {
      System.out.println("Arg: " + signatureArg);
    }
  }

The above code is printing all the arguments i.e. if my URL is

{{base-url}}/v1/login/users/SOMENAME/status it is printing both SOMENAME (path variable) and "sessionGuid" value. I just want to print the value from the header parameter "sessionGuid".

joinPoint.getArgs(); is returning an array. I don't want to print something like arg[1] since sessionGuid may be the 3rd or 4th argument in different operations.

Is there a way by which i can print only "sessionGuid" from the header.


Solution

  • if you are looking for a solution to your problem you can use directly RequestContextHolder.

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String header = request.getHeader("sessionGuid")
    

    you can also use reflection API if you want to be more generic.