spring method validation的不足

建议首先阅读笔者的 spring method validation的实现原理

关于spring method validation,笔者在使用过程中,发现了如下几个问题:

  1. spring method validation 不支持方法对象视图的校验;
  2. 校验过程没有对应的快速失败机制。

关于以上每一点,下面都会进行演示。

第一点: 不支持方法参数对象视图级别的校验
@Validated
public interface PersonService {
    void check(@Validated Element element);
}

@Data
public class Element {
    @NotNull(message = "element name must not be null")
    private String name;
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class ValidatedTest {

    @Autowired
    private PersonService personService;
    
    @Test
    public void test() {
        personService.check(new Element());
    }
}

实际测试证明,在check方法中传人的Element,Element内部的约束是不会生效的。

第二点:没有快速失败机制
例如:
@Validated
public interface PersonService {

    /**
     * check validated annotation active
     *
     * @param element element which to be check
     * @param id      id which to be check
     */
    void check(@NotNull(message = "element must not be null") Element element, @NotNull(message = "id must not be null") Long id);
}

@RunWith(SpringRunner.class)
@SpringBootTest
public class ValidatedTest {

    @Autowired
    private PersonService personService;

    @Test
    public void test() {
        personService.check(null, null);
    }
}

在element校验失败之后,spring validation仍然会校验后面的id属性,这些操作显然是多余的。
下图证明了笔者的观点:在element不符合约束的时候,仍然会校验id属性,所以result中会有两条结果。
在这里插入图片描述

后记:

如何解决这些不足,请参考移步笔者的自己实现method validation


版权声明:本文为wt_better原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。