当前位置:网站首页>Stop using it indiscriminately. This is the real difference between @validated and @valid!!!
Stop using it indiscriminately. This is the real difference between @validated and @valid!!!
2022-06-24 22:43:00 【Migrant worker brother】
Click below “Java Programming duck ” Follow and mark the stars
More exciting First time direct
summary
@ValidIt's usingHibernate validationWhen you use@ValidatedIt's justSpring ValidatorThe verification mechanism uses
explain :java Of JSR303 The statement
@ValidThis kind of interface , andHibernate-validatorIt has been realized
@Validation Yes @Valid Second encapsulation is carried out , There is no difference in use , But in groups 、 Annotation position 、 Nested verification and other functions are different , Here we mainly explain these situations .
Annotation position
@Validated: Used in type 、 Method and method parameters . But it cannot be used for member properties (field)@Valid: It can be used in methods 、 Constructors 、 Method parameters and member properties (field) On
Such as :


If @Validated Annotations on member properties , Will not apply to field error
Group check
@Validated: Provide grouping function , It can be used in parameter verification , Different validation mechanisms according to different groups@Valid: No grouping function
give an example :
Define grouping interface :
public interface IGroupA {
}
public interface IGroupB {
}Define the parameters to be verified bean:
public class StudentBean implements Serializable{
@NotBlank(message = " The username cannot be empty ")
private String name;
// Only when grouped into IGroupB In the case of
@Min(value = 18, message = " Age cannot be less than 18 year ", groups = {IGroupB.class})
private Integer age;
@Pattern(regexp = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$", message = " Mobile number format error ")
private String phoneNum;
@Email(message = " Mailbox format error ")
private String email;
@MyConstraint
private String className;Test code :
The inspection group is IGroupA The situation of
@RestController
public class CheckController {
@PostMapping("stu")
public String addStu(@Validated({IGroupA.class}) @RequestBody StudentBean studentBean){
return "add student success";
}
}test :

Group here IGroupB There is no test
If you change the test code to the following , Look at the test results
@RestController
public class CheckController {
@PostMapping("stu")
public String addStu(@Validated({IGroupA.class, IGroupB.class}) @RequestBody StudentBean studentBean){
return "add student success";
}
}explain :
1、 Regardless of with groups, By default, it should be verified every time
2、 When multiple verification methods are required for a parameter , This can also be achieved by assigning different groups .
Group sequence
By default Different levels of constraint validation are unordered , But in some cases , Sequential verification is very important .
A group can be defined as a sequence of other groups , When it is used for verification, it must conform to the order specified in the sequence . When using group sequence validation , If the group validation before the sequence fails , Then the latter group will no longer give validation .
give an example :
Define group sequence :
@GroupSequence({Default.class, IGroupA.class, IGroupB.class})
public interface IGroup {
}It needs to be verified Bean, Defining the IGroupA Yes age check ,IGroupB Yes className check :
public class StudentBean implements Serializable{
@NotBlank(message = " The username cannot be empty ")
private String name;
@Min(value = 18, message = " Age cannot be less than 18 year ", groups = IGroupA.class)
private Integer age;
@Pattern(regexp = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$", message = " Mobile number format error ")
private String phoneNum; year
@Email(message = " Mailbox format error ")
private String email;
@MyConstraint(groups = IGroupB.class)
private String className;Test code :
@RestController
public class CheckController {
@PostMapping("stu")
public String addStu(@Validated({IGroup.class}) @RequestBody StudentBean studentBean){
return "add student success";
}
}Tests found , If age error , So the group sequence is in IGroupA After IGroupB No verification , In this case className No verification , give the result as follows :

Nested verification
One to be verified pojo class , It also contains the objects to be verified , You need to annotate the object to be verified @Valid, To verify the member properties in the object to be verified , Not available here @Validated.
give an example :
Constraint verification is required bean:
public class TeacherBean {
@NotEmpty(message = " Teacher name cannot be empty ")
private String teacherName;
@Min(value = 1, message = " The types of subjects are from 1 Start calculating ")
private int type;public class StudentBean implements Serializable{
@NotBlank(message = " The username cannot be empty ")
private String name;
@Min(value = 18, message = " Age cannot be less than 18 year ")
private Integer age;
@Pattern(regexp = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(166)|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$", message = " Mobile number format error ")
private String phoneNum;
@Email(message = " Mailbox format error ")
private String email;
@MyConstraint
private String className;
@NotNull(message = " The teacher cannot be empty ")
@Size(min = 1, message = " At least one teacher ")
private List<TeacherBean> teacherBeans;Be careful :
Here to teacherBeans Only verified NotNull, and Size, It did not teacher Check the fields in the information , The specific tests are as follows :

here teacher Medium type Obviously does not conform to the constraint requirements , But it can pass the test , Because in student I didn't do Nested verification
Can be in teacherBeans Medium plus @Valid, As follows :
@Valid
@NotNull(message = " The teacher cannot be empty ")
@Size(min = 1, message = " At least one teacher ")
private List<TeacherBean> teacherBeans;Here's another test , You'll find the following :

source :blog.csdn.net/herojuice/article/
details/86020101
END
After reading this article, there are gains ? Please forward to share with more people
Focus on 「Java Programming duck 」, promote Java Skill
Focus on Java Programming duck WeChat official account , The background to reply : Yard farm gift bag A copy of the latest technical data can be obtained . cover Java Frame learning 、 Architect learning, etc !
If the article helps , Looking at , Forward! .
Thank you for your support (*^__^*)边栏推荐
- New features of go1.18: efficient replication, new clone API for strings and bytes standard library
- Nuscenes -- remedies for missing image files or 0-size images encountered during dataset configuration
- CSRF and SSRF for web attacks
- See how sparksql supports enterprise level data warehouse
- Process communication mode
- seven
- Programmers become gods by digging holes in one year, carrying flags in five years and becoming gods in ten years
- Extend your kubernetes API with aggregated apiserver
- 使用Aggregated APIServer扩展你的kubernetes API
- Redis hop table
猜你喜欢

Data center basic network platform

1. fully explain the basic principles of IPSec

Huada 04A operating mode / low power consumption mode

Seven principles of software design

Information update on automatic control principle

Power system | IEEE paper submission process

Virtual private network foundation

Principles of Ethernet port mirroring, link aggregation and VLAN Technology

Kubevela v1.2 release: the graphical operation console velaux you want is finally here

See how sparksql supports enterprise level data warehouse
随机推荐
find your present (2)
Why can some programmers get good offers with average ability?
Concurrency of heap memory allocation
1. fully explain the basic principles of IPSec
Extend your kubernetes API with aggregated apiserver
电力系统| IEEE论文投稿流程
Fanuc robot_ Introduction to Karel programming (1)
String exercise summary 2
[personal experiment report]
Online filing process
【Mongodb】READ_ME_TO_RECOVER_YOUR_DATA,数据库被恶意删除
结合源码剖析Oauth2分布式认证与授权的实现流程
The difference between get and post
Genesis public chain and a group of encryption investors in the United States gathered in consensus 2022
重磅!法大大上榜“专精特新”企业
Information update on automatic control principle
Web security XSS foundation 06
In the era of industrial Internet, there is no Internet in the traditional sense
软件设计的七大原则
A girl has been making hardware for ten years. 。。