Spring uses @Validated annotation for parameter verification

In the previous project, the parameter verification was done by a judgment method written by myself. This method requires writing a large amount of parameter verification code. This time, the annotation provided by spring is used for parameter verification, which is more convenient ,concise.
@Valid: common use in the process, for the class field validation
@Validated: spring is provided for the encapsulation of @Valid, commonly used in the checksum method, can be regarded as an upgraded version @Valid
Insert picture description here
1. business scenario
using The code of the spring framework, in the new or modified interface of the Controller layer, often directly receives an object parsed by @ResponseBody. After receiving it, an object parameter verification is required to prevent abnormalities in the service layer from affecting the final database storage, etc. Features. Here you can use the @Validated annotation to verify the parameter object. When using, also create a global exception handling intercepted exception information thrown. Another important content here is the grouping function of @Validated. In addition and modification, because the parameters that need to be passed are different, it needs to be distinguished in the receiving object at a time. The specific application is as follows: The first one on the
Controller layer
Insert picture description hereInsert picture description here
is a new interface, and the second is a modified interface. In the new interface, @Validated uses {Insert.class}, which means to use Insert.class in the StocksPrice object. Grouped parameter verification. The update.class is used in the modification interface, which means to use the parameter verification of the Update.class grouping in the StocksPrice object.
The StocksPrice object Insert picture description here
Update.class and Insert.class are two interfaces defined by themselves.
Insert picture description here
Insert picture description here
Global exception handler @RestControllerAdviceInsert picture description here

Guess you like

Origin blog.csdn.net/Wangdiankun/article/details/115184187
Recommended