我创建了一个API并添加了一个自定义批注来验证Request主体对象,但是从未调用过它。下面是对象。请仔细阅读代码,并帮助我在哪里需要更正代码?
@ NotNull,@ Size也不起作用
请求正文对象
@Getter
@AllArgsConstructor
@Sample
public class SaleRequest {
@NotNull
private Integer sale;
@NotNull
private Date dateTime;
@NotNull
@Size(min = 10, max = 10)
private String customerId;
}
注解
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {SalesRequestValidator.class})
@Documented
public @interface Sample {
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
String message() default "Invalid Sale Request";
}
验证器
public class SalesRequestValidator implements ConstraintValidator<Sample, SaleRequest> {
private String message;
@Override
public void initialize(Sample constraintAnnotation) {
this.message = constraintAnnotation.message();
}
@Override
public boolean isValid(SaleRequest sale, ConstraintValidatorContext context) {
System.out.println("Tested!");
return sale.getSale() > 0;
}
}
api实施
public interface SalesApi {
@RequestMapping(
value = {"/sales"},
produces = {"application/json"},
consumes = {"application/json"},
method = {RequestMethod.POST}
)
ResponseEntity<Integer> submitSale(@RequestBody @Valid SaleRequest saleRequest);
}
无法弄清楚我哪里出了错
最佳答案
实施看起来还可以。
确保已在希望接收SaleRequest的请求正文的控制器方法中设置了@Valid
批注。
它看起来应该像这样:addNewSaleRequest(@RequestBody @Valid SaleRequest saleRequest)