Rest学习环境搭建
环境搭建
1.建立父工程
1 | <!--打包方式 pom--> |
2.创建数据库 db01
1 | DROP TABLE IF EXISTS `dept`; |
3.创建springcloud-api 子项目,引入依赖 并 创建实体类
1 | <!--当前Model自己需要的依赖,如果父依赖中已精配置了版本,这里就不用写了--> |
1 | // 实体类 |
4.创建 springcloud-provider-dept-8001 子项目(此项目作为提供者)
4.1.导入依赖
1 | <dependencies> |
4.2.配置yml
1 | server: |
4.3.配置mybatis-config.xml
1 | <configuration> |
4.4.Mapper接口与实现
1 |
|
1 |
|
4.5.Service层
1 | public interface DeptService { |
1 |
|
4.6.Controller层
1 | // 此Controller提供Restful服务 |
4.7.创建SpringBoot启动类,
1 |
|
4.8.启动后,输入http:localhost:8001//dept/get/2 看效果
一个简单的springboot项目搭建完成。
接下来在此基础上面,再搭建一层,用来调用提供者的链接。
5.创建springcloud-consumer-dept-80 子项目,作为消费者
5.1.导入依赖
1 | <dependencies> |
5.2.配置文件
1 | server: |
5.3. 注入 Restful 的 RestTemplate 模板
1 |
|
5.4. 消费者Controller层 调用 提供者的Controller层
要明白:消费者,不应该有service层。
Restful 也对应有其模板RestTemplate(是一个简单的Restful服务模板),模板中提供多种便捷访问远程http服务的方法 供我们直接调用。
restTemplate.getForObject(url(去哪个地方拿), [参数],[返回值类型])
restTemplate.postForObject(。。。)
要把模板注册到Spring中。
1 |
|
5.5. 提供一个SpringBoot启动类
1 |
|
5.6. 启动后,输入 http://localhost:/consumer/dept/get/2 看效果
与提供者层输入 http:localhost:8001//dept/get/2 效果一样。
即相当于在springboot项目上加了一层。