为 REST 请求和响应创建不同的类不好吗?
我正在一个Spring Boot项目中工作,作为我目前的实现,几乎对于每个API,我都有请求和响应类。
例如:
@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;
}
然后,当客户端执行添加通知的请求时,某些字段是否为 null?Email