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?