Java 使用Spring boot ConstraintValidator的多字段验证不起作用
我正在尝试使用spring boot constraintValidator验证多个字段。但它没有嗡嗡声,没有错误 有人能帮我查一下吗 控制器Java 使用Spring boot ConstraintValidator的多字段验证不起作用,java,spring,spring-boot,annotations,Java,Spring,Spring Boot,Annotations,我正在尝试使用spring boot constraintValidator验证多个字段。但它没有嗡嗡声,没有错误 有人能帮我查一下吗 控制器 @PostMapping("/greetings") public Greeting greeting(@RequestBody Greeting greeting) { System.out.println(greeting); return greeting; } public c
@PostMapping("/greetings")
public Greeting greeting(@RequestBody Greeting greeting) {
System.out.println(greeting);
return greeting;
}
public class GreetingValidator implements ConstraintValidator<GreetingAnnotation, Greeting > {
@Override
public boolean isValid(Greeting greeting, ConstraintValidatorContext context) {
return greeting.getId() >=0 && greeting.getContent().length() >=100; // Never gets called
}
}
需要验证的Bean
@GreetingAnnotation
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
注释
@Constraint(validatedBy = GreetingValidator.class)
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface GreetingAnnotation {
String message() default "Field is required";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
@约束(validatedBy=GreetingValidator.class)
@目标(ElementType.TYPE)
@保留(RetentionPolicy.RUNTIME)
public@interface-GreetingAnnotation{
字符串消息()默认为“字段为必填项”;
类[]组()默认值{};
类您是否在控制器级别使用@Validated
如果没有,则添加它。它将起作用。1)将“@Component”注释添加到GreetingValidator类。2)将“@Valid”添加到参数“greeting”:“@RequestBody@Valid greeting”