使用@Before建议将标题添加到RestTemplate

时间:2018-07-13 05:44:23

标签: java spring http aop resttemplate

我在Spring中使用AOP将自定义Header添加到RestTemplate时遇到了麻烦。 我想到的是一些建议,这些建议将通过添加此标头来自动修改RestTemplate.execute(..)的执行。另一个问题是针对特定的RestTemplate实例,该实例是Service的成员,需要传递此标头。

这是我的建议代码,如下所示:

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) {}
}

我遇到的问题是如何修改RequestCallback以添加我的标头。作为一个接口,它看上去相当空虚,另一方面,我宁愿不使用具体的暗示,因为那样的话,我将不得不手动检查实现是否与期望的类匹配。我开始怀疑这是否真的是一种正确的方法。我找到了这个答案Add my custom http header to Spring RestTemplate request / extend RestTemplate 但是,当我在执行路径上检查到正在使用RestTemplate.exchange()时,它将使用RestTemplate.execute()。有人在这里有什么想法吗?

0 个答案:

没有答案