RestTemplate
をアプリケーション起動時に設定する場合は、Springブートアプリケーションの設定クラスで@Bean
注釈を使用します。Spring起動時に@Beanを使用してRestテンプレートを作成または構成する方法
私は、アプリケーションフローのさまざまな場所で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'インスタンスを注入していることを確認です役立ちます今、あなたは
あなたのサービスクラスにBeanをautowireことを願っています他の豆を拾っている? '@ Autowired'アノテーションの隣に' org.springframework.beans.factory.annotation.Qualifier'から '@Qualifier(" appRestClient ")'を追加してみてください。 – Edd
あなたの入力danielに感謝します。私が@Qualifierインタセプタを試してみると、私はここで何かが見つからないと思います。 – springbootlearner