1

I'm having trouble adding a custom Header to a RestTemplate using AOP in Spring. What I have in mind is having some advice that will automatically modify execution of RestTemplate.execute(..) by adding this one Header. Other concern is targeting a particular RestTemplate instance that is a member of a Service which requires having this Header passed.

Here is the code of my Advice as it looks like now:

package com.my.app.web.controller.helper;

import com.my.app.web.HeaderContext;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.RestTemplate;

@Aspect
public class MyAppHeaderAspect {

  private static final String HEADER_NAME = "X-Header-Name";

  @Autowired
  HeaderContext headerContext;

  @Before("withinServiceApiPointcut() && executionOfRestTemplateExecuteMethodPointcut()")
  public void addHeader(RequestCallback requestCallback){
    if(requestCallback != null){
      String header = headerContext.getHeader();
    }
  }

  @Pointcut("within (com.my.app.service.NeedsHeaderService)")
  public void withinServiceApiPointcut() {}

  @Pointcut("execution (* org.springframework.web.client.RestTemplate.execute(..)) && args(requestCallback)")
  public void executionOfRestTemplateExecuteMethodPointcut(RequestCallback requestCallback) {}
}

The problem that I'm having is how to modify RequestCallback to add my header. Being an interface it looks rather empty, on the other hand I'd rather not use a concrete implemntation because then I'd have to manually check if the implementation matches expected class. I'm beginning to wonder if this is really a correct method to do this. I found this answer Add my custom http header to Spring RestTemplate request / extend RestTemplate But it uses RestTemplate.exchange() when I've checked that on my execution path RestTemplate.execute() is being used. Anyone has any ideas here?

Sok Pomaranczowy
  • 993
  • 3
  • 12
  • 32
  • 1
    Why? Just use a `ClientHttpRequestInterceptor` for this instead of AOP and use a custom `RestTemplate` for that specific service. – M. Deinum Jul 13 '18 at 05:47
  • 1
    And here is an excellent post showing what M. Deinum suggested: http://springinpractice.com/2013/10/27/how-to-send-an-http-header-with-every-request-with-spring-resttemplate – Jonck van der Kogel Jul 13 '18 at 05:54
  • I dont think this may be possible for me. The `RestTemplate` I need to change is a member of the `ApiService`. Both classes arrive to me inside a library and I should interact with `RestTemplate` only through service's API. – Sok Pomaranczowy Jul 13 '18 at 06:16

0 Answers0