Initializing objects in Spring Controller - best practise?

Viewed 356

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?

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.

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?

@RestController
@RequestMapping("/api")
public class MyController {

    @Autowired
    private Environment env;
    
    HttpHeaders headers = HeaderService.setHeaders(env);
    RestTemplate restTemplate = new RestTemplate();
public class HeaderService {
    
    private static HttpHeaders httpHeaders;
    
    public static HttpHeaders setHeaders(Environment env) {
        httpHeaders = new HttpHeaders();

        httpHeaders.set("apikey", env.getProperty("apikey"));
        httpHeaders.set("uid", "test");
        httpHeaders.set("Content-Type", env.getProperty("content.type"));
        httpHeaders.set("Accept", env.getProperty("content.type"));
        
        return httpHeaders; 
    }
}

Example of my POST method from which I wan't to get rid of headers and resttemplate instantiation:

    @PostMapping(value = "/addperson")
    public String postPerson(@RequestBody Person person){
        String url = "myurl.com";

        HttpHeaders headers = HeaderService.setHeaders(env);
                
        HttpEntity<Person> requestEntity = 
                new HttpEntity<Person>(person, headers);
        
        RestTemplate restTemplate = new RestTemplate();

        ResponseEntity<String> response = restTemplate.postForEntity(
                url, requestEntity, String.class);      

        return response.getBody();
    }
1 Answers

Just initialize these objects as part of the Spring container. See https://spring.io/guides/gs/consuming-rest/. In a configuration class, you can create the RestTemplate as a bean (similarly for the headers object):

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder.build();
}
Related