我想在 Spring Boot 应用程序的配置类中使用 @Bean
注释将 RestTemplate
定义为应用程序 bean。
我在我的应用程序流程的不同位置调用 4 个休息服务。目前我正在创建 RestTemplate
每次每个请求。有没有一种方法可以使用 --- 将其定义为应用程序 bean 并使用 @Autowired
@Bean
注入它?
这个问题的主要原因是我可以定义 RestTemplate
使用 @Bean
但是当我用 @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 服务并获得响应。
原文由 springbootlearner 发布,翻译遵循 CC BY-SA 4.0 许可协议
从拦截器的名称来看,我猜你正在登录它?您可能会错过 日志级别配置。我使用
1.3.6.RELEASE
版本创建了一个小应用程序来检查您的配置是否有效。在这个类中,我定义了
RestTemplate
bean 和带有日志记录的拦截器。为了使日志记录正常工作,我还必须在
application.properties
中设置正确的调试级别。然后我创建一个服务,在其中注入
RestTemplate
。还有一个端点来测试这一点。
通过执行
GET
请求http://localhost:8080/test
我应该期望得到字符串hello!
被打印(该服务调用http://localhost:8080
返回hello!
并将其发回给我)。带有记录器的拦截器还在控制台中打印出Intercepting...
。