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 ?
Asked
Active
Viewed 1.1k times
12
-
Define an `@Bean`- annotated method in your configuration class, which creates and returns the RestTemplate. http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-java – JB Nizet Jan 06 '17 at 20:48
-
Check out the code on this question for exactly what you're trying to do: http://stackoverflow.com/questions/40473146/java-spring-interceptor-with-no-xml – David Ferris Jan 06 '17 at 21:34
1 Answers
15
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)

Klaus Groenbaek
- 4,820
- 2
- 15
- 30