Bean Validation 如何不重复注解?
How to not repeat annotations for Bean Validation?
我使用 Spring MVC 和表单验证。用户实体有字段登录:
@Pattern(regexp = Constants.LOGIN_PATTERN)
@Size(min = 4, max = 50)
private String login;
但我想将此注释用于其他字段,例如 RegisterData.login。所以我创建了另一个注释:
@Retention(RetentionPolicy.RUNTIME)
@Target(value = { ElementType.FIELD, ElementType.PARAMETER })
@Pattern(regexp = Constants.LOGIN_PATTERN)
@Size(min = 4, max = 50)
public @interface Login {
}
现在用它标记字段。但这是行不通的。是那种'inheritance'的使用方法吗?还是我应该重复一遍?
通过添加 @Constraint
注释,您缺少将 @Login
注释声明为约束。来自 Bean Validation specification:
Composition is done by annotating a constraint annotation with the composing constraint annotations.
由于您的组合约束不需要验证器,您可以将 validatedBy
属性 设置为空数组。
@Pattern(regexp = Constants.LOGIN_PATTERN)
@Size(min = 4, max = 50)
@Constraint(validatedBy = {})
@Target(value = { ElementType.FIELD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface Login {
String message() default "Incorrect login";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
我使用 Spring MVC 和表单验证。用户实体有字段登录:
@Pattern(regexp = Constants.LOGIN_PATTERN)
@Size(min = 4, max = 50)
private String login;
但我想将此注释用于其他字段,例如 RegisterData.login。所以我创建了另一个注释:
@Retention(RetentionPolicy.RUNTIME)
@Target(value = { ElementType.FIELD, ElementType.PARAMETER })
@Pattern(regexp = Constants.LOGIN_PATTERN)
@Size(min = 4, max = 50)
public @interface Login {
}
现在用它标记字段。但这是行不通的。是那种'inheritance'的使用方法吗?还是我应该重复一遍?
通过添加 @Constraint
注释,您缺少将 @Login
注释声明为约束。来自 Bean Validation specification:
Composition is done by annotating a constraint annotation with the composing constraint annotations.
由于您的组合约束不需要验证器,您可以将 validatedBy
属性 设置为空数组。
@Pattern(regexp = Constants.LOGIN_PATTERN)
@Size(min = 4, max = 50)
@Constraint(validatedBy = {})
@Target(value = { ElementType.FIELD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface Login {
String message() default "Incorrect login";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}