javascript
api分层内部外部 spring_java - Spring boot restful API分层架构验证 - SO中文参考 - www.soinside.com...
[今天,我與我們的一位團隊成員就Controller和Service層中的RESTful API輸入的驗證進行了大討論,我覺得這是提出更大論點的糟糕日子。因此,我們有一個具有分層體系結構的spring boot microservice應用程序Controller --> Service --> Repository
參數是在每一層進行驗證還是僅在Controller層進行驗證,例如,我們具有Controller和POST請求,并且對輸入請求主體使用JSR-380驗證
Controller:@PostMapping(value = "/", consumes = {"application/json"}, produces = {"application/json"})
public ResponseEntity createConfig(
@NotNull(message = "{error.message.config_detail}")
@RequestBody @Validated Config config) {
return new ResponseEntity<>(configService.create(config.getConfigId(), config.getTaskId()), HttpStatus.CREATED);
}
Config:請求正文public class Config {
@ApiModelProperty(name = "config_id", example = "1", required = true)
@NotNull(message = "{error.message.config_id}")
private Long configId;
@ApiModelProperty(name = "task_id", example = "11", required = true)
@NotNull(message = "{error.message.task_id}")
@Min(value = 0, message = "{error.message.task_id}")
@Max(value = 9999, message = "{error.message.task_id}")
private Integer taskId;
// bunch of addition fields with validations
}
如果驗證成功,則使用Service中的某些屬性調用Config方法>
服務:public Detail create(@Valid @NotNull Long configId, @NotNull Integer taskId) {
// some business logic to convert to entity and saving to database
return repository.save(entity));
}
因此,如果我們看到上面的代碼,則在Controller和Service處進行相同的驗證,因此我認為無需在Service層進行驗證,請在控制器層執行驗證,并且如果輸入錯誤然后向用戶拋出400或500。 但是團隊中的另一個人也建議在每個塊中對塊中使用的內容進行驗證,以使每段代碼都是安全的(專注于單元而不是集成路徑)。]
我知道在這種情況下我可能是錯的,但是仍然無法理解每一層的驗證(我同意無效檢查,因此建議在每個級別進行驗證的方法Controller --> validation call service
Service ---> validation and call business
Business ---> validation and call repository
Repository --> save根據我的說法,
但是首選的驗證方式是什么?如果Controller輸入是有效的,請調用Service并執行業務邏輯并調用Repository。如果我錯了,請糾正我,以便我可以遵循推薦的模式
今天,我與我們的一位團隊成員就控制器和服務層中的RESTful API輸入的驗證進行了廣泛的討論,我覺得這是提出更大論點的糟糕日子。所以我們有一個...
總結
以上是生活随笔為你收集整理的api分层内部外部 spring_java - Spring boot restful API分层架构验证 - SO中文参考 - www.soinside.com...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ffmpeg库编译加文字_ffmpeg第
- 下一篇: mysql 给字段添加索引_怎么给mys