【发布时间】:2016-11-25 18:41:32
【问题描述】:
我想在 Spring Boot 应用程序的配置类中使用 @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实例,你可能会选择其他一些bean?尝试在@Autowired注释旁边添加来自org.springframework.beans.factory.annotation.Qualifier的@Qualifier("appRestClient")。 -
感谢您的输入 daniel。当我尝试使用 @Qualifier 时,拦截器没有被拾取。我想我在这里遗漏了一些东西。
标签: spring-boot