弹簧方法级验证器

时间:2018-08-29 09:13:16

标签: java spring validation spring-boot

我想验证smalls.add(elMin)的两个参数是否满足我的期望。我创建了一个验证器:

getCategories()

执行:

@Constraint(validatedBy = EnvironmentIdValidator.class)
@Target({METHOD, CONSTRUCTOR})
@Retention(RUNTIME)
@Documented
public @interface IEnvironmentIdValidator {
    String message() default "Invalid environment ID.";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
    String[] value();
}

我正在带有注释的端点之一调用此验证器,同时传递两个参数。

@SupportedValidationTarget(ValidationTarget.PARAMETERS)
public class EnvironmentIdValidator implements ConstraintValidator<IEnvironmentIdValidator,Object[]> {

    @Override
    public void initialize(IEnvironmentIdValidator constraintAnnotation) {
        // logic

    }

    @Override
    public boolean isValid(Object[] object, ConstraintValidatorContext constraintValidatorContext) {
       // logic
    }
}

但是不幸的是,验证器没有被触发。我可能做错了什么?

1 个答案:

答案 0 :(得分:0)

您的控制器必须带有@Validated注释,否则您的bean将不会附加自定义验证。

//...
import org.springframework.validation.annotation.Validated;

@Controller
@Validated
public class MyController {

    @IEnvironmentIdValidator
    @GetMapping("/test/{environmentID}")
    public ResponseEntity<?> getCategories(@PathVariable(name = "environmentID") Long environmentID,
                                      @RequestHeader("Authorization") String requestAuthorizationHeader) {
    //...