上面看到,每个属性只有一种核查规则,但是如果我们要在不同的场景中使用不同的规则,那么这个时候应该怎么办呢,分组就来了,新增一个注解Matchers

    1. @Target(ElementType.FIELD)
    2. @Retention(RetentionPolicy.RUNTIME)
    3. public @interface Matchers {
    4. Matcher[] value();
    5. }

    使用时候,通过属性中的group进行定义不同的规则,核查的时候,采用函数MkValidators.check(String group, Object obj)进行核查,如果采用MkValidators.check(Object obj)则采用默认的组,即下面的没有设置组的匹配规则

    1. @Data
    2. @Accessors(chain = true)
    3. public class GroupEntity {
    4. @Matchers({
    5. @Matcher(range = "[50, 100]", accept = false),
    6. @Matcher(group = "test1", range = "[12, 23]", accept = false),
    7. @Matcher(group = "test2", range = "[1, 10]", accept = false)
    8. })
    9. private Integer age;
    10. @Matchers({
    11. @Matcher(value = {"beijing", "shanghai", "guangzhou"}),
    12. @Matcher(group = "test1", value = {"beijing", "shanghai"}),
    13. @Matcher(group = "test2", value = {"shanghai", "hangzhou"})
    14. })
    15. private String name;
    16. }

    用例

    1. def "测试指定分组"() {
    2. given:
    3. GroupEntity entity = new GroupEntity().setAge(age).setName(name)
    4. expect:
    5. def act = MkValidators.check("test1", entity);
    6. Assert.assertEquals(result, act)
    7. if (!act) {
    8. println MkValidators.errMsg
    9. }
    10. where:
    11. age | name | result
    12. 10 | "shanghai" | true
    13. 12 | "beijing" | false
    14. 23 | "beijing" | false
    15. 50 | "beijing" | true
    16. 100 | "guangzhou" | false
    17. }