SpringBoot - Lombok使用详解3(@NoArgsConstructor、@AllArgsConstructor、@RequiredArgsConstructor)
2024-10-22 14:38:33
五、Lombok 注解详解(3)
5,@NoArgsConstructor
注解在类上,为类提供一个无参的构造方法。
注意:
- 当类中有 final 字段没有被初始化时,编译器会报错,此时可用 @NoArgsConstructor(force = true),然后就会为没有初始化的 final 字段设置默认值 0 / false / null。
- 对于具有约束的字段(例如 @NonNull 字段),不会生成检查或分配,因此请注意,正确初始化这些字段之前,这些约束无效。
1 // 使用注解
2 @NoArgsConstructor
3 public class Shape {
4 private int x;
5 @NonNull
6 private double y;
7 @NonNull
8 private String name;
9 }
10
11 // 不使用注解
12 public class Shape {
13 private int x;
14 private double y;
15 private String name;
16
17 public Shape(){
18 }
19 }
6,@AllArgsConstructor
(1)注解在类上,为类提供一个全参的构造方法。
(2)默认生成的方法是 public 的,如果要修改方法修饰符可以设置 AccessLevel 的值。
- 例如:@Getter(access = AccessLevel.PROTECTED)
1 // 使用注解
2 @AllArgsConstructor(access = AccessLevel.PROTECTED)
3 public class Shape {
4 private int x;
5 @NonNull
6 private double y;
7 @NonNull
8 private String name;
9 }
10
11 // 不使用注解
12 public class Shape {
13 private int x;
14 private double y;
15 private String name;
16
17 protected Shape(int x, double y, String name){
18 this.x = x;
19 this.y = y;
20 this.name = name;
21 }
22 }
7,@RequiredArgsConstructor
(1)注解在类上,会生成构造方法(可能带参数也可能不带参数)。
注意:如果带参数,这参数只能是以 final 修饰的未经初始化的字段或者是以 @NonNull 注解的未经初始化的字段。
(2)该注解还可以用 @RequiredArgsConstructor(staticName="methodName") 的形式生成一个指定名称的静态方法,返回一个调用相应的构造方法产生的对象
1 // 使用注解
2 @RequiredArgsConstructor(staticName = "hangge")
3 public class Shape {
4 private int x;
5 @NonNull
6 private double y;
7 @NonNull
8 private String name;
9 }
10
11 // 不使用注解
12 public class Shape {
13 private int x;
14 private double y;
15 private String name;
16
17 public Shape(double y, String name){
18 this.y = y;
19 this.name = name;
20 }
21
22 public static Shape hangge(double y, String name){
23 return new Shape(y, name);
24 }
25 }
最新文章
- NS2中修改载波侦听范围和传输范围
- ThroughRain第二次冲刺(每天更新
- 四 mybatis开发dao的方法
- meta是什么意思?
- the partition number
- ThinkPHP删除栏目(多)
- App Inventor2项目部署到本地
- GDI与GDI+性能比较
- Android开发之如何避免ANR(Keeping Your App Responsive)
- ES6 原始类型 Symbol
- 小技巧css解决移动端ios不兼容position:fixed属性,无需插件
- no matching editors or conversion strategy found
- Spring boot实现自定义拦截器
- 洛谷 P5089: CodeForces #500 (Div. 1) B / 1012B : Chemical table
- 练习题 --- 写出5种css定位语法
- 从0开始学习 GITHUB 系列之「GIT 进阶」【转】
- git squash 和 git rebase
- Tempdb--查看tempdb使用的脚本
- Win10系统中新增的快捷键,做个记录
- bootstrap基本用法