![](/img/trans.png)
[英]Add prefix or suffix to the GET,PUT,POST,DELETE mappings in controller at method level using custom annotation - Spring REST Controller
[英]Method level custom constraint not fired on Spring controller REST method
我正在為 Spring REST 方法創建自定義方法級別約束,但根本沒有觸發驗證器。 isValid
方法永遠不會被調用。
//
// Controller
//
@PostMapping("/{id}")
@DTOParametersMatch
public ResponseEntity<DTO> createDTO(
@PathVariable("id") @SuppressWarnings("unused") UUID id,
@Validated(CreateValidation.class) @RequestBody DTO dto
) {
System.out.println("***** createDTO called");
DTO created = dtosService.createDTO(dto);
return ResponseEntity.status(HttpStatus.CREATED).body(created);
}
//
// DTOParametersMatch
//
@Constraint(validatedBy = DTOParametersMatchValidator.class)
@Target({ METHOD, CONSTRUCTOR })
@Retention(RUNTIME)
@Documented
public @interface DTOParametersMatch {
String message() default "DTO ID in path must match DTO ID in body";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
//
// DTOParametersMatchValidator
//
@SupportedValidationTarget(PARAMETERS)
public class DTOParametersMatchValidator implements ConstraintValidator<DTOParametersMatch, Object[]> {
private static final String ILLEGAL_ARGS_BASE =
"Illegal usage of DTOParametersMatch; "
+ "requires two parameters where first is a UUID and second is a DTO.";
@Override
public boolean isValid(Object[] values, ConstraintValidatorContext context) {
System.out.println("***** DTOParametersMatchValidator isValid called");
var pathId = (UUID)v0;
var body = (DTO)v1;
return pathId.equals(body.getId());
}
}
我不確定我是否錯過了什么或設置錯誤..
我的一位同事指出我缺少@Validated
上的 @Validated 注釋。 一旦我添加了,一切正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.