I want to define RestTemplate
as an application bean using @Bean
annotation in my configuration class in a spring boot application.
I am calling 4 rest services in different places in my application flow. Currently I am creating RestTemplate
every time every request. Is there a way I can define that as application bean using @Bean
and inject that using @Autowired
?
Main reason for this question is I can able to define RestTemplate
using @Bean
but when I inject it with @Autowired
I am loosing all defined interceptors (Interceptors are not getting called.)
Configuration Class
@Bean(name = "appRestClient")public RestTemplate getRestClient() { RestTemplate restClient = new RestTemplate( new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory())); List<ClientHttpRequestInterceptor> interceptors = new ArrayList<ClientHttpRequestInterceptor>(); interceptors.add(new RestServiceLoggingInterceptor()); restClient.setInterceptors(interceptors); return restClient;}
Service Class
public class MyServiceClass { @Autowired private RestTemplate appRestClient; public String callRestService() { // create uri, method response objects String restResp = appRestClient.getForObject(uri, method, response); // do something with the restResp // return String }}
It seems my Interceptors
are not getting called at all with this configuration. But RestTemplate
is able to make a call to the REST service and get a response.