0
我正在構建一個API,並且構建了我的資源類以使用JsonViews根據api接收到的請求過濾某些字段。我已經得到了正常的工作,但現在,我試圖進行一些性能升級,其中資源上的某些字段甚至沒有計算出來。我在想,如果我能以某種方式創建一個條件表達式來評估哪個JsonView被使用,那可能是一個起點 - 但是,我不確定這種方法。有沒有更好的辦法?依賴於Spring中的JsonView的條件表達式
我已經走到這一步:
Photo.java:
public class Photo {
@JsonView(Views.Public.class)
private Long id;
...
JsonView(Views.PublicExtended.class)
private Double numLikes;
...
Photo(PhotoEntity entity){
this.id = entity.getId();
...
}
Photo(PhotoEntity entity, OtherObject oo){
this.id = entity.getId();
this.numLikes = oo.getNumLikes();
}
PhotoController.java
@JsonView(Views.Public.class)
@RequestMapping(value = "/user/{user_id}", method = RequestMethod.GET)
public ResponseEntity<List<Photo>> getAllForUser(@PathVariable("user_id") Long userId) throws NotFoundException {
return super.ok(svc.getAllForUser(userId));
}
@JsonView(Views.PublicExtended.class)
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ResponseEntity<PhotoResource> getOne(@PathVariable("id") Long id) throws NotFoundException {
return super.ok(svc.getOne(id));
}
PhotoService.java
public Photo entityToResource(PhotoEntity entity) {
// TODO : [Performance] Depending on the view that the controller received, construct the resource with/without OtherObject
String view = "View.PublicExtended.class";
Photo resource;
if(view.equals("View.Public.class")){
resource = new Photo(entity);
}
else{
resource = new Photo(entity, this.getOtherObject(entity));
}
return resource;
}