@Valid不抛出异常 [英] @Valid not throwing exception
问题描述
我正在尝试使用@Valid验证我的JPA实体,如下所示:
I'm trying to validate my JPA Entity with @Valid like this:
public static void persist(@Valid Object o)
它可以工作一段时间,但是现在停止工作了,我不确定为什么.我尝试在persist
方法内手动进行操作,并且按预期方式工作:
It worked fine for a while but now it stopped working and I'm not sure why. I tried to do it manually inside the persist
method, and it works as expected:
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(o);
if (!constraintViolations.isEmpty()) {
throw new ConstraintViolationException(constraintViolations);
}
会发生什么或如何调试呢?
What could be happening or how can I debug this?
推荐答案
不适用于任意服务.在泽西岛,它仅适用于资源方法.因此,请在您的资源方法中验证传入的DTO.
Won't work on arbitrary services. In Jersey it will only work for resource methods. So validate the incoming DTO in your resource method.
@POST
public Response post(@Valid SomeDTO dto) {}
请参见 Bean验证支持
因此,为了回答OP关于如何使它在任意服务上工作的评论,我创建了一个小项目,您可以将其插入并播放到您的应用程序中.
So to answer the OP's comment about how we can make it work on arbitrary services, I created a small project that you can plug and play into your application.
您可以在 GitHub(jersey-hk2-validate)上找到它.
请查看项目中的测试.您还将在此找到完整的JPA示例.
Please look at the tests in the project. You will find a complete JPA example in there also.
克隆,构建并将其添加到您的Maven项目
Clone, build, and add it your Maven project
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);
The key point is to make your service implementation implement Validatable
.
实现的详细信息在README中.但要点是,它利用了 HK2 AOP .因此,您的服务将需要由HK2管理才能正常运行.这就是ValidationFeature
为您服务的.
The details of the implementation are in the README. But the gist of it is that it makes use of HK2 AOP. So your services will need to be managed by HK2 for it to work. That is what the ValidationFeature
does for you.
这篇关于@Valid不抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!