Spring Boot 配置多个 RestTemplate 实例
Spring Boot RestTemplate About 1,463 words场景
工程中需要配置不同处理器的RestTemplate
,比如:有些场景使用默认的ErrorHandler
不处理400
/500
异常,有些场景需要添加Interceptors
拦截器。
代码
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
interceptors.add(new ClientHttpRequestInterceptor() {
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
request.getHeaders().set("my-header", "my-value");
return execution.execute(request, body);
}
});
restTemplate.setInterceptors(interceptors);
return restTemplate;
}
@Bean
public RestTemplate myRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
restTemplate.setErrorHandler(new ResponseErrorHandler() {
@Override
public boolean hasError(ClientHttpResponse response) throws IOException {
return false;
}
@Override
public void handleError(ClientHttpResponse response) throws IOException {
}
});
return restTemplate;
}
}
使用
@Slf4j
@RestController
public class TestController {
@Autowired
private RestTemplate restTemplate;
@Autowired
private RestTemplate myRestTemplate;
}
Views: 1,053 · Posted: 2024-04-04
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...