@Valid not throwing exception

↘锁芯ラ 提交于 2019-12-11 03:54:51

问题


I'm trying to validate my JPA Entity with @Valid like this:

public static void persist(@Valid Object o)

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?


回答1:


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) {}

See more at Bean Validation Support


UPDATE

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.

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

Please look at the tests in the project. You will find a complete JPA example in there also.

Usage

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) {}
}

Then use the ValidationFeature to bind the service

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.

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.




回答2:


Method Validations is only available starting in bean validation v 1.1 (e.g. hibernate validator 5.x impl) which is part of Java EE 7 only. On top of that to have it working without extra specific BV code your method must be part of a component which is integrated with bean validation (eg. CDI Beans, JAX-RS Resource). Your custom code works because you do not use method validation but rather BV constraints which are defined directly on your object.



来源:https://stackoverflow.com/questions/32611262/valid-not-throwing-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!