2017-12-06 23 views
0

스프링 부트를 사용하고 있습니다. 모든 응답의 헤더에 필드를 추가하고 싶습니다. 그래서, 나는 요격기를 사용합니다.스프링 부트 인터셉터를 사용하여 헤더에 필드를 더 추가하십시오.

@Component 
public class ApiVersionInterceptor extends HandlerInterceptorAdapter{ 
    private final Logger log = LoggerFactory.getLogger(ApiVersionInterceptor.class); 

    @Autowired 
    private Environment environment; 

    @Override 
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
           Object handler, Exception arg3) throws Exception { 
     String apiVersion = environment.getProperty(ApiVersion.VERSION_KEY.getKey()); 
     log.debug("api-version:"+apiVersion); 
     response.addHeader("Api-Version", apiVersion); 
    } 
} 

그리고 구성은 다음과 같습니다 : 코드는

@Configuration 
public class InterceptorsConfiguration extends WebMvcConfigurerAdapter { 

    @Autowired 
    private ApiVersionInterceptor apiVersionInterceptor; 

    /** 
    * Add interceptor 
    */ 
    @Override 
    public void addInterceptors(final InterceptorRegistry registry) { 

     //Add api-version field to header of response 
     registry.addInterceptor(apiVersionInterceptor); 
    } 

} 

때문에의 실행이 코드를 냈다 확인하려면 :

2017-12-06 02:35:10,392 DEBUG [] [http-nio-8080-exec-7] ApiVersionInterceptor: api-version:1.9.0 

하지만 난, 난 돈을 이해하지 못하는 응답의 헤더에이 필드가 표시되지 않습니다.

업데이트

내 응용 프로그램을 사용 평안한 웹 서비스, 그래서보기의 위상이 없습니다.

도움 주셔서 감사합니다.

답변

1

이전 단계에서 헤더를 추가하고 ApiVersionInterceptorpreHandle 메서드를 재정의해야합니다. afterCompletion에 응답이 이미 커밋되어 있으므로 헤더가 변경됩니다.

+0

'prehandle()'또는'postHandle()'을 사용하는 경우. 아무 일도 일어나지 않는다. –

+0

작은 데모를 만들었고 restClient가 스크린 샷에 [ScreenShot] (http://prntscr.com/hjq9lj) 링크가 있는지 확인했습니다. 그것은 이상한데, 왜 그것이 당신을 위해 작동하지 않았다. 필요하다면이 데모에 대한 의견을 말하면됩니다. – borino

+0

도움 주셔서 대단히 감사합니다. 나는 작은 프로젝트를 만들고 다시 점검 할 것이다. 그리고 내 회사의 프로젝트이기 때문에 프로젝트를 추진할 수 없습니다. –