How to inject RestTemplate

Ravi picture Ravi · Jan 6, 2017 · Viewed 7.7k times · Source

I am not using xml configurations to define beans. Instead using component scanning and autowire to define and inject dependencies. RestTemplate is part of springframework. How can I inject this class ?

Answer

Klaus Groenbaek picture Klaus Groenbaek · Jan 6, 2017

You do it like any other @Bean in a @Configuration class, and inject with @Autowire - However you question suggest that you should read a little more of the Spring documentation.

    @Bean 
    public RestTemplate restTemplate() {
        RestTemplate template = new RestTemplate();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(100);
        connectionManager.setDefaultMaxPerRoute(6);
        template.setRequestFactory(new HttpComponentsClientHttpRequestFactory(HttpClients.custom().setConnectionManager(connectionManager).build()));
        return template;
    }

You almost always want to use it together with Apache HttpClient so you get connection pooling. If you need to use it with self-signed https certificates you need a bit more code (let me know if this is the case)