title: Initializing objects in Spring Controller - best practise?
body: <p>I have a simple Spring Boot REST API in which I have 6x basic POST and PUT methods. All of these how ever use RestTemplate and HttpHeaders classes that I do not wish to instantiate on every method, because I wan't to avoid boilerplate code. Where should I initialize these classes so that I can use them in the Constructor methods?  Is creating a @PostConstruct the right way to go? <br/>
  <br/>
  I've created a HeaderService class, that takes application.properties as Environmental properties from which it reads the headers and then sets them, and returns HttpHeaders object.<br/>
  <br/>
  I would like to initialize the classes like this, but it does not obviously work. And if I create a @PostController, how can I access these instances?</p>
  <pre><code>@RestController
  @RequestMapping(&quot;/api&quot;)
  public class MyController {
  
      @Autowired
      private Environment env;
      
      HttpHeaders headers = HeaderService.setHeaders(env);
      RestTemplate restTemplate = new RestTemplate();
  </code></pre>
  <pre><code>public class HeaderService {
      
      private static HttpHeaders httpHeaders;
      
      public static HttpHeaders setHeaders(Environment env) {
          httpHeaders = new HttpHeaders();
  
          httpHeaders.set(&quot;apikey&quot;, env.getProperty(&quot;apikey&quot;));
          httpHeaders.set(&quot;uid&quot;, &quot;test&quot;);
          httpHeaders.set(&quot;Content-Type&quot;, env.getProperty(&quot;content.type&quot;));
          httpHeaders.set(&quot;Accept&quot;, env.getProperty(&quot;content.type&quot;));
          
          return httpHeaders; 
      }
  }
  </code></pre>
  <p>Example of my POST method from which I wan't to get rid of headers and resttemplate instantiation:</p>
  <pre><code>    @PostMapping(value = &quot;/addperson&quot;)
      public String postPerson(@RequestBody Person person){
          String url = &quot;myurl.com&quot;;
  
          HttpHeaders headers = HeaderService.setHeaders(env);
                  
          HttpEntity&lt;Person&gt; requestEntity = 
                  new HttpEntity&lt;Person&gt;(person, headers);
          
          RestTemplate restTemplate = new RestTemplate();
  
          ResponseEntity&lt;String&gt; response = restTemplate.postForEntity(
                  url, requestEntity, String.class);      
  
          return response.getBody();
      }
  </code></pre>