@Pattern的元注释在春季不起作用

Nan*_*Rao 1 java annotations bean-validation

注释如下:

@Pattern(regexp = "^[0-9]+$")
@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface MyTestAnnotation {

}
Run Code Online (Sandbox Code Playgroud)

当我用@MyTestAnnotion注释一个字段时,即使该字段不包含所有数字,该呼叫也会顺利进行。

以下部分已由以下给出的答案解决。主要问题仍然存在。我尝试添加:

@Pattern(regexp = "^[0-9]+$")
@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {})
public @interface MyTestAnnotation {

}
Run Code Online (Sandbox Code Playgroud)

在我的@MyTestAnnotation上,它不会让我输入message属性,但是当我运行代码时,它给出了错误,指出未指定message属性。

如果我将@Pattern批注直接放在字段上,则其行为将符合预期。

我在这里想念什么吗?

M. *_*num 5

您的注释错误。有关约束的最小属性,请参见bean验证规范的3.1.1节,以及有关如何进行适当组合的3.3节

您的注释缺少messagegroupspayload属性。

@Pattern(regexp = "^[0-9]+$")
@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {})
public @interface MyTestAnnotation {

    String message() default "{com.acme.constraint.MyConstraint.message}";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}
Run Code Online (Sandbox Code Playgroud)

没有这些属性,您的注释将不被视为约束。