lombok能通过注解的方式,在编译时自动为属性生成构造器,getter/setter、equals、hashcode、toString方法。
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.14</version> <scope>provided</scope> </dependency>
把bean改成lombok添加**@Accessors(chain = true)**注解即可
package com.change.entity; import lombok.Data; import lombok.experimental.Accessors; @Accessors(chain = true) @Data public class UserDemo { private Long id; private String username; private String password; }
链式编程的使用
package com.change; import com.change.entity.UserDemo; public class demo { public static void main(String[] args) { UserDemo userDemo=new UserDemo(); userDemo.setId(1L).setUsername("aa").setPassword("abc"); } }
静态链接编程创建对象更简洁,可以在静态方法,静态代码块等中使用,对于必输字段,也可以强制要求
比如,创建Student对象是没有会要求一些必输字段,比如name字段必须有值,如果自己写
public class StudentBean { private String name; private int age; private StudentBean(String name) { //默认构造方法置为 private this.name = name; } public static StudentBean getInstance(String name) { //唯一的 public 构造方法,name 不能为空 if (name == null) throw new NullPointerException("name is not null"); return new StudentBean(name); } //------------ getter/setter -------------- public StudentBean setName(String name) { this.name = name; return this; // 返回this } public StudentBean setAge(int age) { this.age = age; return this; // 返回this } public String getName() { return this.name; } public int getAge() { return this.age; } public String toString() { return "StudentBean(name=" + getName() + ", age=" + getAge() + ")"; } }
使用lombok注解,实现静态的链式编程
@Accessors(chain = true) @Data @RequiredArgsConstructor(staticName = "getInstance") //指定构造方法 public class StudentBean { @NonNull private String name; private int age; }
在使用的时候
package com.change; import java.math.BigDecimal; public class demo2 { public static void main(String[] args) { StudentBean studentBean = StudentBean.getInstance("lisi").setAge(20); } }
@RequiredArgsConstructor原理
import lombok.NonNull; public class StudentBean { @NonNull private String name; private int age; // 默认构造方法置为 private private StudentBean(@NonNull String name) { if (name == null) throw new NullPointerException("name"); this.name = name; } //唯一的 public 构造方法,name 不能为空 public static StudentBean getInstance(@NonNull String name) { return new StudentBean(name); } //------------ getter/setter -------------- public StudentBean setName(@NonNull String name) { if (name == null) throw new NullPointerException("name"); this.name = name; return this; // 返回this } public StudentBean setAge(int age) { this.age = age; return this; // 返回this } @NonNull public String getName() { return this.name; } public int getAge() { return this.age; } public String toString() { return "StudentBean(name=" + getName() + ", age=" + getAge() + ")"; } // -- 省略 equals,canEqual ,hashCode--- }