springboot 3.x
首先在springboot專案的pom.xml中匯入
<!-- lombok,可以簡化實體類宣告--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> </dependency>
載入完成後就可以在實體類中使用了
原始碼
package com.example.pojo; public class User { private Integer id; private String name; private Short age; private Short gender; private String phone; public User() { } public User(Integer id, String name, Short age, Short gender, String phone) { this.id = id; this.name = name; this.age = age; this.gender = gender; this.phone = phone; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Short getAge() { return age; } public void setAge(Short age) { this.age = age; } public Short getGender() { return gender; } public void setGender(Short gender) { this.gender = gender; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", gender=" + gender + ", phone='" + phone + '\'' + '}'; } }
使用 lombok後
其中@data等價於以下四個註解
@Getter get方法
@Setter set方法
@ToString tostring方法
@EqualsAndHashCode equals和hashcode方法
package com.example.pojo; import lombok.*; //用於存放實體類 @Data @NoArgsConstructor //無參構造 @AllArgsConstructor //全參構造 public class User { private Integer id; private String name; private Short age; private Short gender; private String phone; }
可以看出使用 lombok 註解後程式碼簡化了很多