Java 如何在验证器类中使用注释?
我知道这听起来很奇怪,但我需要在我的项目中满足这样的要求。让我们谈正题吧 我创建了一个自定义注释,它还使用了Java 如何在验证器类中使用注释?,java,validation,annotations,Java,Validation,Annotations,我知道这听起来很奇怪,但我需要在我的项目中满足这样的要求。让我们谈正题吧 我创建了一个自定义注释,它还使用了@Constraint,并在另一个实现ConstraintValidator接口的类中实现了我的自定义验证逻辑。不幸的是,javax.validation从未作为依赖项添加到此项目(@Valid,@NotBlank,@Email等不起作用),因此我被迫实现验证程序接口 我知道我可以将我的自定义逻辑放入Validator的validate()方法(尝试过了,效果很好),但我更愿意保留我的自定
@Constraint
,并在另一个实现ConstraintValidator
接口的类中实现了我的自定义验证逻辑。不幸的是,javax.validation
从未作为依赖项添加到此项目(@Valid
,@NotBlank
,@Email
等不起作用),因此我被迫实现验证程序
接口
我知道我可以将我的自定义逻辑放入Validator
的validate()
方法(尝试过了,效果很好),但我更愿意保留我的自定义注释,以防将来“项目标准”发生变化时其他开发人员需要它
我可以从验证器实例调用注释的isValid()
方法吗?考虑到我不被允许添加依赖项,这是可能的,还是仍然是明智的做法
TLDR代码片段:(写在我的头上,如果有语法错误,很抱歉)
自定义注释
@Retention(RUNTIME)
@Target({TYPE})
@Constraint(validatedBy = myCustomValidator.class)
public @interface myCustomAnnotation {
String message() default "dummy";
Class[] groups() default {};
Class[] payload() default {};
class myCustomValidator implements ConstraintValidator<myCustomAnnotation, Object> {
// @Overload initialize
// some code here
// @Overload isValid
public boolean isValid(Object object, ConstraintValidatorContext ctx) {
// some code here, simple return for demonstration purposes
return object != null;
}
}
}
验证程序的预期用途
public class customValidator implements Validator {
//@Override supports
//@Override validate
public void validate(Object target, Errors errors) {
// somehow invoke my custom annotation here, no other validation code should be here
}
}
public ModelAndView customController(@ModelAttribute("form") CustomForm form, BindingResult errors) {
Validator validator = new CustomValidator();
validator.validate(form, errors);
// expecting errors.hasErrors() to be filled
// ...
}