【发布时间】:2016-09-20 02:01:14
【问题描述】:
我正在一个 Spring Boot 项目中工作,作为我目前的实现,几乎每个 API 我都有 request 和 response 类。
例如:
@RequestMapping(value = "/notice", method = RequestMethod.POST)
public AddNoticeResponse addNotice(@Valid @RequestBody AddNoticeRequest){
Notice notice = ... // creating new notice from AddNoticeRequest
noticeRepository.save(notice);
AddNoticeResponse response = ... // creating new response instance from Notice
return response;
}
请求和响应类如下所示:
@Data
@AllArgsConstructor
public class AddNoticeRequest{
private String subject;
private String message;
private Long timeToLive;
}
// Ommiting some annotations for brevity
public class AddNoticeResponse{
private String subject;
private String message;
private Long timeToLive;
private Date createTime;
private String creator;
}
我有两个问题。
- 创建太多类并命名它们有时让我抓狂。
- 有些请求和响应有共同的字段。
例如:Notice有两种:Email和Notification:
public class Email {
private String subject;
private String message;
private String receiver;
}
那么,我应该使用扩展公共类的内部类还是将所有字段放入一个类中?哪个更好?
public class AddNoticeRequest {
private String subject;
private String message;
class Email extends AddNoticeRequest{
private String receiver;
}
}
public class AddNoticeRequest{
private String subject;
private String message;
private Long timeToLive;
private String receiver;
}
那么当客户端执行添加Email通知的请求时,会不会有些字段为空?
【问题讨论】: