title: How to Create or configure Rest Template using @Bean in Spring Boot
body: <p>I want to define <code>RestTemplate</code> as an application bean using <code>@Bean</code> annotation in my configuration class in a spring boot application.</p>
  
  <p>I am calling 4 rest services in different places in my application flow. Currently I am creating <code>RestTemplate</code> every time every request. Is there a way I can define that as application bean using <code>@Bean</code> and inject that using <code>@Autowired</code>?</p>
  
  <p>Main reason for this question is I can able to define <code>RestTemplate</code> using <code>@Bean</code> but when I inject it with <code>@Autowired</code> I am loosing all defined interceptors (Interceptors are not getting called.)</p>
  
  <p><strong>Configuration Class</strong></p>
  
  <pre><code>@Bean(name = "appRestClient")
  public RestTemplate getRestClient() {
  
      RestTemplate  restClient = new RestTemplate(
          new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));
  
      List&lt;ClientHttpRequestInterceptor&gt; interceptors = new ArrayList&lt;ClientHttpRequestInterceptor&gt;();
      interceptors.add(new RestServiceLoggingInterceptor());
      restClient.setInterceptors(interceptors);
  
      return restClient;
  }
  </code></pre>
  
  <p><strong>Service Class</strong></p>
  
  <pre><code>public class MyServiceClass {
  
      @Autowired
      private RestTemplate appRestClient;
  
      public String callRestService() {
          // create uri, method response objects
          String restResp = appRestClient.getForObject(uri, method, response);
          // do something with the restResp
          // return String
      }
  }
  </code></pre>
  
  <p>It seems my <code>Interceptors</code> are not getting called at all with this configuration. But <code>RestTemplate</code> is able to make a call to the REST service and get a response.</p>