【问题标题】:Spring boot cannot access @Value inside ClientHttpRequestInterceptorSpring boot 无法访问 ClientHttpRequestInterceptor 内的@Value
【发布时间】:2017-01-12 22:42:08
【问题描述】:

我正在使用 spring-boot-1.3.3。我想拦截 Rest 模板,我能够拦截它,但我无法访问 application.properties。它总是返回 null。

package com.sample.filter;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class HeaderInterceptor implements ClientHttpRequestInterceptor{

private static final String CLIENT_HEADER = "x-client";

@Value("${clientHeader}")
private String ClientHeader;

@Override
public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] body, ClientHttpRequestExecution execution) throws IOException {
    HttpHeaders headers = httpRequest.getHeaders();
    headers.add(CLIENT_HEADER, ClientHeader);
    return execution.execute(httpRequest, body);
}
}

我总是将 "clientHeader" 键设为 null。

任何帮助都应该是可观的。

【问题讨论】:

  • 你不是自己创建拦截器吗? (new HeaderInterceptor() 在你的代码中)?
  • 是的。我正在创建拦截器,并在restTemplate setInterceptors 方法中添加此拦截器。它工作正常。只是我想测试我们是否可以使用@Value 动态传递值,但它失败了。
  • 就像 ritesh 所建议的那样,即使您已将 HeaderInterceptor 注释为由 spring(@Component) 管理。但是通过使用 new 运算符,实例化的 HeaderInterceptor 不是 spring 管理的,因此无法访问任何上下文值。拦截器在您的情况下有效,因为没有任何东西阻止流程(只是 clientHeader 属性变为空)。自动装配 HeaderInterceptor 并在 restTemplate 的 setInterceptor 方法中使用该自动装配属性。值可以动态传递。

标签: spring-mvc spring-boot resttemplate spring-restcontroller spring-rest


【解决方案1】:

我看到您在评论中提到您正在通过new 关键字在代码中自己创建拦截器。为了使用 HeaderInterceptor 的 spring 上下文实例,您需要在代码中 autowire 它。只有这样,它才能看到 spring 托管属性。

【讨论】:

    【解决方案2】:

    您可以为拦截器配置@Bean,这将确保@Autowired 字段确实是自动装配的,然后使用它们来配置客户端。

    之前:

    client.setInterceptors(new ClientInterceptor[] {new CustomInterceptor()});
    

    之后:

     @Bean
     public CustomInterceptor customInterceptor() {
        return new CustomInterceptor();
     }
    
     //in the client construction, set the interceptor as below.
     client.setInterceptors(new ClientInterceptor[] {customInterceptor()});
    
     
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-23
      • 1970-01-01
      • 2018-10-15
      • 2019-05-24
      • 2017-04-25
      • 2017-04-13
      相关资源
      最近更新 更多