title: Spring Controllers: Adding a response header parameter called Elapsed-Time
body: <p>I would like to add an Elapsed-Time response header parameter on every API REST request, even those that finish with error.</p>
  
  <p>For instance:</p>
  
  <pre><code>===&gt;
  GET /api/customer/123 HTTP/1.1 
  Accept: application/vnd.company.app.customer-v1+json 
  
  &lt;===
  HTTP/1.1 200 OK 
  Content-Type: application/vnd.company.app.customer-v1+json 
  Elapsed-Time: 12 
  
  { id: 123, name: Jordi, age: 28 }
  </code></pre>
  
  <p>Being Elapsed-Time parameter calculated as the difference in milliseconds between the instant that the @RequestMapping method finishes, and the instant that the @RequestMapping method starts.</p>
  
  <p>I have been taking a look on Spring4 HandlerInterceptorAdapter. preHandle and postHandle methods seem to fit perfectly for this case (despite the time overhead of executing every interceptor in the chain). But, unfortunatelly, changing response header in postHandle method has no effect because the response is already build.</p>
  
  <p><a href="https://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-handlermapping-interceptor" rel="nofollow noreferrer">Spring documentation</a> states:</p>
  
  <blockquote>
    <p>Note that the postHandle method of HandlerInterceptor is not always ideally suited for use with @ResponseBody and ResponseEntity methods. In such cases an HttpMessageConverter writes to and commits the response before postHandle is called which makes it impossible to change the response, for example to add a header. Instead an application can implement ResponseBodyAdvice and either declare it as an @ControllerAdvice bean or configure it directly on RequestMappingHandlerAdapter.</p>
  </blockquote>
  
  <p>Do you know of any working elegant solution to deal with this case?</p>
  
  <p>I don't think think this case is duplicating <a href="https://stackoverflow.com/questions/30702970/spring-modifying-headers-for-every-request-after-processing-in-posthandle">Spring - Modifying headers for every request after processing (in postHandle)</a> because I need to capture a variable whose value is the start time (when petition gets to the application and before the @RequestMapping method starts), and then use this variable once the @RequestMapping method finishes, to compute the elapsed time.</p>