Spring - mixing annotation and validator-based val

2019-07-30 19:57发布

问题:

I've following problem, there's a regular spring model (let's call it "A") with some validations-related annotations. Next, there's a command object (regular POJO class that defines some field, one of them is object of type A). The command object implements Validator interface, to make binding and validation work in controller methods.

Question is, how to make use of annotations-configured validations inside the command object (given it implements Validator interface, hence it has supports() and validate() methods).

What I'm trying to achive is to have basic validations on model that is reused and mixed with some heavier business-logic validations in other parts of the system.

回答1:

I have had the exact same problem. I wanted to use automatic annotation validation for "simple things" and then pass the complex validation logic to my custom spring Validator. But whenever I set the controller validator, all of hibernate's validation stopped working, as described at the end of this tutorial:

http://www.captaindebug.com/2011/07/applying-custom-spring-validator-to.html#.VQR0OI7F-gd

This technique should be used when you need to do ALL your controller’s validation yourself, and you can’t or don’t want to make use of the Hibernate’s reference implementation of a JSR 303 validator. From this, you’ll guess that you can’t mix your own custom Spring validator with Hibernate’s JSR 303 validator. For example, adding the built-in annotations to the Address command object will have no effect:

You should forget about old style Spring Validator and delete "setInitBinder()" as described in this related question:

Spring MVC validator annotation + custom validation

You should then only rely on hibernate validation and JSR303.

To add a complex validation to your class (model), say you want to check two date fields - use a custom annotation constraint on class level as described in the link below.

https://docs.jboss.org/hibernate/validator/5.1/reference/en-US/html/validator-customconstraints.html#section-class-level-constraints

Hope this helps.

Best Regards, Alexander



回答2:

Once look at this may this help you Using both JSR-303 and Traditional Bean Validation?. There i have given one example for custom validation for model using custom annotation.