使用@Bean我想定義RestTemplate
如使用我的配置類@Bean
標註在春季啓動應用程序的應用程序配置豆休息模板。如何創建或在春季啓動
我打電話在不同的地方休息4個服務於我的應用程序流。目前我每次請求時都會創建RestTemplate
。有沒有一種方法可以將應用程序bean定義爲使用@Bean
並使用@Autowired
注入?
對這個問題的主要原因是,我可以能夠使用@Bean
定義RestTemplate
但是當我@Autowired
注入它,我失去了所有定義攔截(攔截器沒有得到調用。)
配置類
@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;
}
服務類
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
}
}
看來我Interceptors
沒有得到調用此配置在所有。但是RestTemplate
能夠調用REST服務並獲得響應。
你確定你注入相同'RestTemplate'例如,您可能正在撿一些其他豆嗎?嘗試在'@ Autowired'註記旁邊的'org.springframework.beans.factory.annotation.Qualifier'中添加'@Qualifier(「appRestClient」)''。 – Edd
感謝您的輸入daniel.When我試過@Qualifier攔截器沒有得到拾起。我想我在這裏失去了一些東西。 – springbootlearner