java – Hibernate Validator. How do I use @ valid annotation?
What is the purpose of placing the @ valid annotation at the method parameter level?
public void (@Valid Person p) { ... }
I created a test and passed this method to an invalid object, but there was no response I hope to get an exception
Solution
The @ valid annotation on the object indicates that the validation framework handles annotated objects When used on method parameters, this is called method - level validation Please note that method level validation is not part of the core specification. In fact, it is only supported when bean validation is integrated into the container type framework (JSF, CDI, Java EE) When bean validation is integrated into such a supporting container, what will happen is that when the lifecycle method is called on the bean, the container will detect the JSR 303 annotation on the method parameters and trigger the validation of the associated bean
For example, if you have the following method definitions in the jax-rs resource class:
@Path("/example") public class MyExampleResourceImpl { @POST @Path("/") public Response postExample(@Valid final Example example) { // .... } }
The sample bean is validated when the postexample method is called in response to a request processed by the jax-rs container Compare this behavior to what happens when you run a stand-alone Java se application:
public class MyMainClass { public static void main(final String[] args) { final MyMainClass clazz = new MyMainClass(); clazz.echo(new Example()); } public Example echo(@Valid final Example example) { // ... } }
In this case, even if you include all JSR 303 runtime jars, running the program will not trigger the validation of the example parameter This is because no container is available to implement method level validation The bean validation specification describes all of these in detail in Appendix C For your benefit, I quote some contents below: