13.07.2015 Views

JSR 303 的参考实现使用指南 - JBoss

JSR 303 的参考实现使用指南 - JBoss

JSR 303 的参考实现使用指南 - JBoss

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

第 3 章 创 建 自 己 的 约 束 规 则}}assertEquals(0, constraintViolations.size());3.2. 约 束 条 件 组 合在 例 3.7 “ 应 用 CheckCase 约 束 条 件 ” 中 我 们 可 以 看 到 , 类 Car 的 licensePlate 属 性 上 定 义 了 三 个约 束 条 件 . 在 某 些 复 杂 的 场 景 中 , 可 能 还 会 有 更 多 的 约 束 条 件 被 定 义 到 同 一 个 元 素 上 面 , 这 可 能会 让 代 码 看 起 来 有 些 复 杂 , 另 外 , 如 果 在 另 外 的 类 里 面 还 有 一 个 licensePlate 属 性 , 我 们 可 能 还要 把 这 些 约 束 条 件 再 拷 贝 到 这 个 属 性 上 , 但 是 这 样 做 又 违 反 了 DRY 原 则 .这 个 问 题 可 以 通 过 使 用 组 合 约 束 条 件 来 解 决 . 接 下 来 让 我 们 来 创 建 一 个 新 的 约 束 标注 @ValidLicensePlate, 它 组 合 了 @NotNull, @Size 和 @CheckCase:例 3.9. 创 建 一 个 约 束 条 件 组 合 ValidLicensePlatepackage com.mycompany;import static java.lang.annotation.ElementType.*;import static java.lang.annotation.RetentionPolicy.*;import java.lang.annotation.Documented;import java.lang.annotation.Retention;import java.lang.annotation.Target;import javax.validation.Constraint;import javax.validation.Payload;import javax.validation.constraints.NotNull;import javax.validation.constraints.Size;@NotNull@Size(min = 2, max = 14)@CheckCase(CaseMode.UPPER)@Target( { METHOD, FIELD, ANNOTATION_TYPE })@Retention(RUNTIME)@Constraint(validatedBy = {})@Documentedpublic @interface ValidLicensePlate {String message() default "{com.mycompany.constraints.validlicenseplate}";Class[] groups() default {};Class

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!