到目前為止,我有一個端點,如下所示:
@PostMapping(path = "/my-endpoint")
public ResponseEntity<Void> method(@PathVariable("id") String id,
@RequestBody @Valid MyClass<MyType> body) {
// custom logic in here
return ResponseEntity.ok().build();
}
在對該端點執行 POST 請求時,物件錯誤時的驗證會正確執行并400: Bad Request
顯示出來。
但是,現在由于某些代碼情況,我想從外部觸發該方法RestController
并通過Consumer
.
新代碼如下:
@Bean
public Consumer<Message<String>> consumer(MyController myController) {
message -> myController.method("sampleId", message); // message here is parsed to the class, so the proper type is sent to the controller method.
}
每當我檢查呼叫時,無論發送什么輸入myController.method
,代碼總是。200: OK
有沒有辦法觸發未通過 REST API 發送的驗證?
uj5u.com熱心網友回復:
我建議首先將自定義邏輯從控制器移動到帶@Service
注釋的類。
然后注入驗證器@Autowired private Validator validator;
并觸發驗證。
public void myServiceMethod(MyMessage message) {
Set<ConstraintViolation<MyMessage>> violations = validator.validate(message);
if (!violations.isEmpty()) {
// ...
}
}
https://www.baeldung.com/spring-service-layer-validation
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/506760.html