Spring boot не может получить доступ к @Value внутри ClientHttpRequestInterceptor

Я использую spring-boot-1.3.3. Я хочу перехватить шаблон Rest, и я могу перехватить его, но не могу получить доступ к application.properties. Он всегда возвращает ноль.

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" как ноль.

Любая помощь должна быть заметной.

1 ответ

Решение

Я вижу, вы упомянули в своем комментарии, что вы сами создаете перехватчик в коде new ключевое слово. Чтобы использовать экземпляр контекста Spring HeaderInterceptor, вам нужно автоматически связать его с вашим кодом. Только тогда он будет иметь видимость управляемых пружиной свойств.

Вы можете настроить @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()});

 
Другие вопросы по тегам