Spring Boot中的自定义参数验证器

时间:2019-05-22 20:44:58

标签: java spring-boot customvalidator

我创建了一个自定义验证器,以验证传递给转换器中函数的String。但是,没有调用自定义验证器。我想念什么吗?

OperationParameter.java

@Documented
@Constraint(validatedBy = OperationParameterValidation.class)
@Target( { ElementType.PARAMETER
        })
@Retention(RetentionPolicy.RUNTIME)
public @interface OperationParameter {
    String message() default "Operation Parameter Invalid";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };
}

OperationParameterValidation.java

public class OperationParameterValidation implements ConstraintValidator<OperationParameter, String> {

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
       System.out.println("Validator called");
        // validation process
        // return true / false;
    }

}

converter.java

@Component
public class StringToOperation implements Converter<String, Operation> {

    @Override
    public Operation convert(@Valid @OperationParameter String source) {
         // Even I pass wrong String this function is executed successfully, and no print from validator
    }
}

Service.java

public class Service {

    @Autowired
    ConversionService conversionService;

    public void action() {

        String action = "";
        Operation addInsertOperation = conversionService.convert(action, Operation.class);
    }

}

1 个答案:

答案 0 :(得分:0)

在验证器类上设置@SupportedValidationTarget(ValidationTarget.PARAMETERS)