1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public class Order { // 必须不为 null, 大小是 10 @NotNull @Size(min = 10, max = 10) private String orderId; // 必须不为空 @NotEmpty private String customer; // 必须是一个电子信箱地址 private String email; // 必须不为空 @NotEmpty private String address; // 必须不为 null, 必须是下面四个字符串'created', 'paid', 'shipped', 'closed'其中之一 // @Status 是一个定制化的 contraint @NotNull @Status private String status; // 必须不为 null @NotNull private Date createDate; // 嵌套验证 @Valid private Product product; … getter 和 setter } |
1 2 3 4 5 6 7 8 9 10 11 | public class Product { // 必须非空 @NotEmpty private String productName; // 必须在 8000 至 10000 的范围内 // @Price 是一个定制化的 constraint @Price private float price; … Getter 和 setter } |
1 2 3 4 5 6 7 8 9 | // 'to'所表示的日期必须在'from'所表示的日期之后 // @QueryConstraint 是一个定制化的 constraint @QueryConstraint public class OrderQuery { private Date from; private Date to; … omitted … Getter and setter } |
1 2 3 4 5 6 7 8 9 10 11 12 | // @Max 和 @Min 都是内置的 constraint @Max(10000) @Min(8000) @Constraint(validatedBy = {}) @Documented @Target( { ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) public @interface Price { String message() default "错误的价格"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; } |
1 2 3 4 5 6 7 8 9 | @Constraint(validatedBy = {StatusValidator.class}) @Documented @Target( { ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD }) @Retention(RetentionPolicy.RUNTIME) public @interface Status { String message() default "不正确的状态 , 应该是 'created', 'paid', shipped', closed'其中之一"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; } |
欢迎光临 电子技术论坛_中国专业的电子工程师学习交流社区-中电网技术论坛 (http://bbs.eccn.com/) | Powered by Discuz! 7.0.0 |