我创建了自定义 ContrainValidator 并添加了以下代码。 我还添加了我的控制器类。不知何故,代码没有在验证器中流动。
ValidCustomClass 类
package com.validation;
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Documented
@Constraint(validatedBy = MyValidator.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
public @interface ValidCustomClass {
String message() default "Invalid request.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
验证器类
package com.validation;
import com.model.request.CreateRequest;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MyValidator implements ConstraintValidator<ValidCustomClass, CreateRequest> {
private static final String MY_REGEX = "^(.+)@(.+)$";
public MyValidator() {
}
@Override
public void initialize(ValidCustomClass constraintAnnotation) {
// DO nothing here
}
@Override
public boolean isValid(final CreateRequest value, final ConstraintValidatorContext context) {
if (dosSomething(value)) return false;
return true;
}
}
控制器类
package com.controller;
import com.model.request.CreateRequest;
import com.model.response.MyResponse;
import com.service.MyService;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Validated
@RequestMapping("/endpoint")
public class MyController {
private final MyService myService;
MyController(MyService myService) {
this. myService = myService;
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public MyResponse create(@RequestBody @Valid CreateRequest request) throws Exception {
return myService.create(request);
}
}
最后我在
@ValidCustomClass
上添加了CreateRequest
。
我在这里遗漏了什么吗?没有错误,但未调用验证器。
你错过了两点。首先,注释应该是这样的
@Documented
@Constraint(validatedBy = MyValidator.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
public @interface ValidCustomClass {
String message() default "Invalid request";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
其次,类或类中的字段应该使用这样的自定义注释进行注释
@ValidCustomClass
public class CreateRequest {
}