1. Research javax.mail. Validation. Constraints. NotNull operation principle
1.1. Source code follow-up
- In order to find
NotNull
Where exactly is it being processed, so I print an error message, and according to the keyword of the error message, the first thing I find is this place, you can see it’s webMVC package, understandable, after all, it’s requested through the interface and intercepted, it needs to go through WebMVC, right
- The next step is to explore how this statement is generated. Trace back to the source of the body value and find out where the exception was finally caught
DispatcherServlet
Class, feel ready to find, enter the handle method
- Keep looking inside and find the toss
MethodArgumentNotValidException
Where there’s an exception, you can see that the way to validate the parameters isvalidateIfApplicable
- If you go into this method, you can see your familiar friends,
@Validated
This annotation needs to be added to any Controller interface that needs validation, and the core validation method after that isbinder.validate
And then there are a lot of layers of branching, so I’m going to talk about a real problem I encountered finding the source path
Problem of 1.2.
- Only in the
controller
Layer, write a@Validated
Notes, after@NotNull
Annotations such as judgment are only available@Validated
The defined object is in effect, and now I want to implement itObjects within objects also implement validationI’m just going to jump to the conclusion here, so I wrote the following class, and I need the body object to be able to validate as well, so I add a@Valid
Annotation can be achieved, then look at the source code
@data public class Request<T> {/** * Request body */ @valid private T body; /** * private Integer requestCode; */ private Map<String,Object> extend; }Copy the code
- Due to the depth of too many layers, I will pick a few key screenshots, play a role in the role of the deep understanding must look at their own source code
-
The core class is validated with the SpringValidatorAdapter
-
I’m going to go through the annotations, and I’m going to skip a few layers
-
Finally found the @VALID annotation that gets the object property
-
Now that I have this cascading metadata, which I’ll use for subsequent judgments, valueContext, I’ve set the id attribute of the ExampleDeleteVo object to @notnull
- And you can see that it gets a value with ID null and puts it in
currentValue
1.3. Summarize
In the beginning, I looked at the @validated annotation to see if there was a way to validate the “Validated” object within an object. If not, I might have to write my own interceptor method. I don’t want to duplicate the “wheel” until I have to. If you have patience to finish reading this article, it is estimated that you have encountered the problem of @vaildated. I hope it can play a role in drawing inspiration from others