使用@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