我已經定義了兩個 Spring Boot REST 資源
POST /customer
以上資源用于添加具有以下 JSON 作為請求的客戶
{
"customerFirstName" : "John"
"customerLastName" : "Doe"
"customerAddress" : {
"addressLine1" : "22 XYZ Drive"
"addressLine1" : "22 suite"
"state" : "PY"
"country" : "Ind"
"zipCode" : "1235312"
}
}
現在我需要實作更新客戶資訊,因此定義了以下資源。要求是任何與客戶相關的資訊都可以更新。因此,更新時的 Input JSON 與添加請求時的輸入 JSON 相同。唯一需要注意的是,未提供的資訊將不會更新。只有提供的資訊才會更新。
PUT /customer/{customerId}
問題:我想使用 Spring boot Bean 請求驗證。但是,添加和更新資源的驗證要求不同,因此無法使用相同的Customer域模型。但是,這兩種情況下的域模型完全相同,因此這會導致代碼重復。我怎樣才能避免這種情況,或者將驗證移到外面并編碼是否正確。
示例:在添加客戶的情況下,必須提供客戶地址,因此可以使用諸如@NotNull. 但是,在更新客戶的情況下,客戶地址不是必需的。
uj5u.com熱心網友回復:
您應該能夠使用驗證組并保留一個模型類。每個約束都有groups可用于定義驗證方案的屬性。您可以擁有一個Create僅在 POST 請求中使用而在 PATCH 中忽略的組:
interface Create {}
class Customer {
@NotNull(groups = Create.class)
private String firstName;
@NotNull(groups = Create.class)
private String lastName;
//....
}
然后,當您使用 Spring 時,您可能需要查看@Validated注釋。這個允許您定義要驗證的特定組:
@PostMapping("/customer")
public ResponseEntity<Customer> create(@RequestBody @Validated(Create.class) Customer customer) {
// do your thing
}
您還可以查看檔案的這一部分以了解有關組及其功能的更多資訊
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/359675.html
