@Valid 不抛出异常

@Valid not throwing exception

我正在尝试使用 @Valid 验证我的 JPA 实体,如下所示:

public static void persist(@Valid Object o)

有一段时间它运行良好,但现在它停止运行了,我不确定为什么。我尝试在 persist 方法中手动完成,它按预期工作:

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    Set<ConstraintViolation<Object>> constraintViolations = validator.validate(o);

    if (!constraintViolations.isEmpty()) {
        throw new ConstraintViolationException(constraintViolations);
    }

可能发生了什么或者我该如何调试?

方法验证仅从 bean 验证 v 1.1(例如 hibernate validator 5.x impl)开始可用,它仅是 Java EE 7 的一部分。最重要的是,要使其在没有额外特定 BV 代码的情况下工作,您的方法必须是与 bean 验证集成的组件的一部分(例如 CDI Beans、JAX-RS Resource)。您的自定义代码之所以有效,是因为您不使用方法验证,而是使用直接在对象上定义的 BV 约束。

不适用于任意服务。在泽西岛,它只适用于资源方法。因此,请在您的资源方法中验证传入的 DTO。

@POST
public Response post(@Valid SomeDTO dto) {}

Bean Validation Support

查看更多

更新

因此,为了回答 OP 关于我们如何让它在任意服务上运行的评论,我创建了一个小项目,您可以在您的应用程序中即插即用。

You can find it on GitHub (jersey-hk2-validate).

请查看项目中的测试。您还将在其中找到完整的 JPA 示例。

用法

克隆、构建并将其添加到您的 Maven 项目

public interface ServiceContract {
    void save(Model model);
}

public class ServiceContractImpl implements ServiceContract, Validatable {
    @Override
    public void save(@Valid Model model) {}
}

然后使用ValidationFeature绑定服务

ValidationFeature feature = new ValidationFeature.Builder()
        .addSingletonClass(ServiceContractImpl.class, ServiceContract.class).build();
ResourceConfig config = new ResourceConfig();
config.register(feature);

重点是让你的服务实现实现Validatable.

实现的细节在 README 中。但它的要点是它利用了 HK2 AOP。因此,您的服务需要由 HK2 管理才能运行。这就是 ValidationFeature 为您所做的。