当前位置:网站首页>@Constructorproperties annotation understanding and its corresponding usage
@Constructorproperties annotation understanding and its corresponding usage
2022-07-26 06:28:00 【Bo · Meng】
List of articles
1. Say first conclusion
@ConstructorProperties annotation Not at all json Inside , It is jdk Classes carried by itself .

When a class has Multiple constructors , It's going on json When converting to an object , When you need to specify which constructor it uses , have access to @ConstructorProperties annotation , tell json In the process of transformation , Which constructor to use to deserialize as an object .
By default, without any other conditions ,json When deserializing to an object using a constructor :
- If there is a parameterless constructor , And when there is a parameter constructor , first Will choose Parameter free constructor Deserialization .
- If there are multiple parameterized constructors , But there is no parameterless constructor , first Will choose The parameterized constructor with the most parameters Deserialization .
- In both cases , If new conditions @ConstructorProperties Annotations of words , first choice Constructor annotated by this Deserialization .
@ConstructorProperties A note Can replace json In the annotations @JsonCreator And @JsonProperty At the same time .
stay springboot Use in @ConstructorProperties annotation , The function of its annotation parameters is completely invalid , The function of this annotation is only : tell ObjectMapper Use that constructor to deserialize , The cause has not been found .
2. Get started using
1. @JsonCreator And @JsonProperty Use
@JsonCreator Specify which constructor to use for deserialization .
@JsonProperty Appoint json Object field name , Correspondence with specific attribute names .
The code is as follows :
@ToString public class AA { private String name; private String password; public AA(String name){ System.out.println(" Use a constructor with only one parameter "); this.name = name; } // Specify to use this constructor for deserialization // @JsonProperty("pwd") named , attribute password And json Of pwd The corresponding field @JsonCreator public AA(@JsonProperty("name") String name, @JsonProperty("pwd") String password) { System.out.println(" All parameter constructor is used "); this.name = name; this.password = password; } }public class demo { public static void main(String[] args) throws Exception{ String jsonStr = "{\n" + " \"name\":\"1\",\n" + " \"pwd\":\"123\"\n" + "}"; ObjectMapper objectMapper = new ObjectMapper(); final AA aa = objectMapper.readValue(jsonStr, AA.class); System.out.println(aa); } }
2. @ConstructorProperties Use
@ConstructorProperties Completely replaceable @JsonCreator And @JsonProperty.
Annotation parameters are specified json Field , And Constructors The correspondence of parameters , Binding relationship .
The code is as follows :
@ToString public class AA { private String name; private String password; public AA(String name){ System.out.println(" Use a constructor with only one parameter "); this.name = name; } // The annotation parameter specifies json Field , And Constructors The correspondence of parameters // Attribute password And json Of pwd The corresponding field // Attribute namee And json Of name The corresponding field @ConstructorProperties({ "name", "pwd"}) public AA(String name, String password) { System.out.println(" All parameter constructor is used "); this.name = name; this.password = password; } }public class demo { public static void main(String[] args) throws Exception{ String jsonStr = "{\n" + " \"name\":\"1\",\n" + " \"pwd\":\"123\"\n" + "}"; ObjectMapper objectMapper = new ObjectMapper(); final AA aa = objectMapper.readValue(jsonStr, AA.class); System.out.println(aa); } }
The @ConstructorProperties annotation The parameter is to specify json Field , And Constructors The correspondence of parameters
Change the code to @ConstructorProperties({“pwd”, “name”})@ToString public class AA { private String name; private String password; public AA(String name) { System.out.println(" Use a constructor with only one parameter "); this.name = name; } // Willingly The correspondence is reversed // So the binding relationship here is : // json Of pwd Corresponding name // json Of name Corresponding password @ConstructorProperties({ "pwd", "name"}) public AA(String name, String password) { System.out.println(" All parameter constructor is used "); this.name = name; this.password = password; } } public class demo { public static void main(String[] args) throws Exception{ String jsonStr = "{\n" + " \"pwd\":\"123\",\n" + " \"name\":\"1\"\n" + "}"; ObjectMapper objectMapper = new ObjectMapper(); final AA aa = objectMapper.readValue(jsonStr, AA.class); System.out.println(aa); } }
It can be seen from the above figure , Original name=1, Now it is name=123
3. Verification conclusion
1. Prepare for
Below ObjectMapper, All are be based on ObjectMapper, After all, it is springboot Default json Transformation tools .
Prepare an entity class , One controller layer :
@ToString public class AA { private String name; private String password; public AA(String name){ System.out.println(" Use a constructor with only one parameter "); this.name = name; } public AA(String name, String password) { System.out.println(" All parameter constructor is used "); this.name = name; this.password = password; } public AA(){ System.out.println(" Use parameterless constructor "); } } @RestController public class ConstructorTestController { @PostMapping("/test/A") public void testA(@RequestBody AA a){ System.out.println(a); } }stay AA On entity class , Only add @ToString Method , For the convenience of viewing its attribute assignment , There is no way to add @Getter perhaps @Setter annotation , because json The transformation can also be based on these two methods , You can refer to :(ObjectMapper)Json The basic principle of transforming objects
Based on the third point above , Do a little science popularization ,json The transformation of Priority of usage yes :set Method 、public Of field attribute 、get Method 、 Constructors .
2. Verify the existence of both nonparametric and parametric structures
Nonparametric structure and parametric structure exist at the same time , Priority is the parameterless constructor :

If... Is used at this time @ConstructorProperties({“name”, “password”}), Priority is the constructor specified by the annotation
@ToString public class AA { private String name; private String password; public AA(String name) { System.out.println(" Use a constructor with only one parameter "); this.name = name; } @ConstructorProperties({ "name", "password"}) public AA(String name, String password) { System.out.println(" All parameter constructor is used "); this.name = name; this.password = password; } public AA() { System.out.println(" Use parameterless constructor "); } }
3. Verify that only With parameter constructor
When there is only a parameter constructor , Without any other comments , The priority is Constructor with the most parameters deserialize .
The code is as follows :
@ToString public class AA { private String name; private String password; public AA(String name) { System.out.println(" Use a constructor with only one parameter "); this.name = name; } public AA(String name, String password) { System.out.println(" All parameter constructor is used "); this.name = name; this.password = password; } }
Some people might say , Because it's just right json There are two fields , All constructors that use full parameters , Now we change it to only name Field json request :

It can be seen from the above that , priority : Is the constructor with the most parametersWhen we use @ConstructorProperties annotation , The annotation parameter is written name,password


Or the annotation parameters are only written name

4. stay springboot Use in @ConstructorProperties When the annotation , Parameter function completely fails
In the QuickStart , We Mention of @ConstructorProperties Annotated parameters , Yes, it will json Field corresponds to the parameters of its constructor
But after testing , stay springboot in , It doesn't seem like this , The code is as follows :
The corresponding relation is :json Field of pwd Corresponding attribute name,json Field of name Corresponding attribute password@ToString public class AA { private String name; private String password; public AA(String name) { System.out.println(" Use a constructor with only one parameter "); this.name = name; } @ConstructorProperties({ "pwd", "name"}) public AA(String name, String password) { System.out.println(" All parameter constructor is used "); this.name = name; this.password = password; } }

边栏推荐
- YOLOv6:又快又准的目标检测框架开源啦
- How can machinery manufacturing enterprises do well in production management with the help of ERP system?
- Code Runner for VS Code,下载量突破 4000 万!支持超过50种语言
- 2022年下半年系统集成项目管理工程师(软考中级)报名条件
- [day_040421] calculate candy
- Code runner for vs code, with more than 40million downloads! Support more than 50 languages
- 性能测试包括哪些方面?分类及测试方法有哪些?
- 带你搞透IO多路复用原理(select、poll和epoll)
- redis 哨兵集群搭建
- 【Day02_0419】C语言选择题
猜你喜欢

机械制造企业如何借助ERP系统,做好生产管理?

移动web
![[nanny level] package volume optimization tutorial](/img/45/4ca66b10bb96efeb47501c07972d66.png)
[nanny level] package volume optimization tutorial

输入5个学生的记录(每条记录包括学号和成绩), 组成记录数组, 然后按照成绩由高到低的次序输出. 排序方法采用选择排序

【C语言】文件操作

Swift basic FileManager (file management)

分布式 | 实战:将业务从 MyCAT 平滑迁移到 dble

Find the original root

Jz36 binary search tree and bidirectional linked list

Meiker Studio - Huawei 14 day Hongmeng equipment development practical notes 4
随机推荐
[day_050422] continuous maximum sum
【pytorch】CNN实战-花朵种类识别
PG vacuum auto vacuum
移动web
Input the records of 5 students (each record includes student number and grade), form a record array, and then output them in order of grade from high to low The sorting method adopts selective sortin
Three skills are needed to engage in SAP related work
[pytorch] picture enlargement
Servlet cannot directly obtain JSON format data in request request
[day_070425] Fibonacci series
MySQL multi table query introduction classic case
[day02_0419] C language multiple choice questions
Liberg avenue to Jane series
PG Vacuum 杂谈之 auto vacuum
【Day_04 0421】计算糖果
Code runner for vs code, with more than 40million downloads! Support more than 50 languages
定义方法时为什么使用static关键字
C language file operation
Cdga | how to build data asset catalogue?
Mobile web
What is spark serialization for?