【发布时间】:2018-03-03 09:34:50
【问题描述】:
我正在使用 Spring Boot 创建一个 RESTful API。我有需要向资源提出请求的要求
/用户/通知
通知资源将接受 bodyrequest 中的值并将通知发送给用户。
@ResponseBody
@RequestMapping(value = "/user/notification", method = RequestMethod.POST)
public NotificationResponse sendNotification(@Valid @RequestBody NotificationRequest notificationRequest){
// here is code where I need to build right
// object of type text/file/link/map (please read full question below)
notificationService.send(notificationRequest.getUsername(), object);
}
它接受:用户名和通知数据。这是 NotificationRequest 类:
public class NotificationRequest {
@NotEmpty
private String username;
@NotEmpty
private String type;
private String title;
@NotEmpty
private String content;
private String url;
private String longitude;
private String latitude;
private String file_url;
//getters and setters
}
我有 4 种类型的通知,即。文本、链接、地图和文件。它们的属性就是这些。
text
- type
- title
- content
link
- type
- title
- content
- url
map
- type
- title
- longitude
- latitude
file
- type
- title
- content
- file_url
我为这些创建了 4 个类,所以我可以创建正确的对象,如您所见,type 和 title 是常见的属性,所以我使用了继承。
public class NotificationBase {
private String type;
private String title;
//getters and setters here
}
并像这样扩展了其他 4 个类。
public class TextNotification extends NotificationBase {
private String content;
//getters and setters here
}
我的问题是,我如何创建我的类,以便
如果有人想发送文本通知,我可以得到一个 TextNotification 对象,如果有人想发送文件通知,我可以创建 FileNotification 对象吗?
注意:请注意,在这种情况下,我不想使用 gJson 或 Jackson 创建 JSON 对象。
如果我需要在此处添加更多信息,请告诉我。
【问题讨论】:
-
type的属性是NotificationRequest的实际类型(文本、地图等)吗?如果是这样,只需根据该类型进行实例化。否则,您可以将通知类型作为 url 上的查询参数。您可以根据需要将创建过程抽象为工厂或其他东西,但这是最简单的解决方案
标签: java oop spring-boot