112 lines
2.5 KiB
Markdown
112 lines
2.5 KiB
Markdown
|
### 任务名称: Restful接口回应数据的统一封装
|
|||
|
#### 目标:
|
|||
|
- 掌握Spring Boot框架基本层次结构
|
|||
|
- 掌握接口的统一返回格式的设计和实现
|
|||
|
- 泛型的使用
|
|||
|
- lombok的使用
|
|||
|
- spring配置文件中自定义属性
|
|||
|
#### 预备知识:
|
|||
|
- 泛型
|
|||
|
|
|||
|
#### 操作步骤:
|
|||
|
##### 1. 项目java包结构设计
|
|||
|
创建包:controller、entity、repository、service、dto、 dto.rest.response
|
|||
|
|
|||
|
##### 2. 实现类Result
|
|||
|
```java
|
|||
|
package com.lk.paopao.dto.rest.response;
|
|||
|
|
|||
|
import lombok.Getter;
|
|||
|
|
|||
|
import java.io.Serializable;
|
|||
|
|
|||
|
@Getter
|
|||
|
public class Result implements Serializable {
|
|||
|
int code;
|
|||
|
String msg;
|
|||
|
public Result(int code, String message) {
|
|||
|
this.code = code;
|
|||
|
this.msg = message;
|
|||
|
}
|
|||
|
}
|
|||
|
|
|||
|
```
|
|||
|
|
|||
|
##### 3. 实现类DataResult
|
|||
|
DataResult继承Result,添加data属性,通过泛型来确定data的类型。
|
|||
|
```java
|
|||
|
package com.lk.paopao.dto.rest.response;
|
|||
|
|
|||
|
import lombok.Getter;
|
|||
|
import java.io.Serializable;
|
|||
|
|
|||
|
@Getter
|
|||
|
public class DataResult<T> extends Result implements Serializable {
|
|||
|
|
|||
|
T data;
|
|||
|
|
|||
|
public DataResult(int code, T data, String message){
|
|||
|
super(code, message);
|
|||
|
this.data = data;
|
|||
|
}
|
|||
|
|
|||
|
}
|
|||
|
|
|||
|
```
|
|||
|
##### 4. 实现类DataResult
|
|||
|
|
|||
|
通过工具类ResultUtil,实现ok、fail方法, 返回DataResult对象。
|
|||
|
|
|||
|
此工具类简化创建DataResult对象的过程。
|
|||
|
|
|||
|
```java
|
|||
|
package com.lk.paopao.dto.rest.response;
|
|||
|
|
|||
|
|
|||
|
public class ResultUtil {
|
|||
|
public static <T> DataResult<T> ok(T data) {
|
|||
|
return new DataResult<T>(0, data, "SUCCESS");
|
|||
|
}
|
|||
|
|
|||
|
public static Result ok() {
|
|||
|
return new Result(0, "SUCCESS");
|
|||
|
}
|
|||
|
|
|||
|
public static Result fail(String error) {
|
|||
|
return new Result(500, error);
|
|||
|
}
|
|||
|
|
|||
|
public static Result fail(int code, String error) {
|
|||
|
return new Result(code, error);
|
|||
|
}
|
|||
|
|
|||
|
}
|
|||
|
```
|
|||
|
|
|||
|
##### 5. 自定义API接口版本号
|
|||
|
在application.yml配置文件中添加如下配置:
|
|||
|
```yaml
|
|||
|
|
|||
|
app:
|
|||
|
version: v1
|
|||
|
default:
|
|||
|
head-icon: https://assets.paopao.info/public/avatar/default/joshua.png
|
|||
|
|
|||
|
|
|||
|
```
|
|||
|
|
|||
|
|
|||
|
#### 技术/工具需求:
|
|||
|
- [列出完成任务所需的技术栈、工具、软件版本等。]
|
|||
|
|
|||
|
#### 成功标准:
|
|||
|
- [明确完成任务的评判标准,如代码功能实现、性能指标、测试通过条件等。]
|
|||
|
|
|||
|
#### 扩展学习(可选):
|
|||
|
- [提供一些额外学习资源或挑战性任务,鼓励学有余力的学生进一步探索。]
|
|||
|
|
|||
|
#### 评估与反馈:
|
|||
|
- [说明如何提交作业、代码审查的标准、或任何反馈收集机制。]
|
|||
|
|
|||
|
#### 时间估算:
|
|||
|
- [给出预计完成该任务所需的时间,帮助学生合理安排学习计划。]
|