基于SpringBoot的RestTemplate
为什么要学习RestTemplate?
RestTemplate是一个执行HTTP请求的同步阻塞式工具类,它仅仅只是在 HTTP 客户端库(例如 JDK HttpURLConnection,Apache HttpComponents,okHttp 等)基础上,封装了更加简单易用的模板方法 API,方便程序员利用已提供的模板方法发起网络请求和处理,能很大程度上提升我们的开发效率
一、环境配置
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
将RestTemplate
配置初始化为一个Bean
@Configuration
public class RestTemplateConfig {/*** 没有实例化RestTemplate时,初始化RestTemplate* @return*/@ConditionalOnMissingBean(RestTemplate.class)@Beanpublic RestTemplate restTemplate(){RestTemplate restTemplate = new RestTemplate();return restTemplate;}
}
二、如何使用
在需要使用的方法中注入
/*** @RequiredArgsConstructor 用于给加final的成员变量添加构造函数* 等价于* public CartServiceImpl (RestTemplate restTemplate){* this.restTemplate = restTemplate;* }*/private final RestTemplate restTemplate;