Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject RestTemplate

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 ?

like image 529
Ravi Avatar asked Jan 06 '17 20:01

Ravi


1 Answers

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)

like image 154
Klaus Groenbaek Avatar answered Oct 19 '22 14:10

Klaus Groenbaek