1. 程式人生 > >今天 1024,為了不 996,Lombok 用起來以及避坑指南

今天 1024,為了不 996,Lombok 用起來以及避坑指南

# Lombok簡介、使用、工作原理、優缺點 Lombok 專案是一個 Java 庫,它會自動插入編輯器和構建工具中,Lombok 提供了一組有用的註解,用來消除 Java 類中的大量樣板程式碼。 --- [TOC] --- # 簡介 **官方介紹** > > Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java. Never write another getter or equals method again, with one annotation your class has a fully featured builder, automate your logging variables, and much more. 翻譯之後就是: Lombok 專案是一個 Java 庫,它會自動插入您的編輯器和構建工具中,簡化您的 Java 。 不需要再寫另一個 getter、setter、toString 或 equals 方法,帶有一個註釋的您的類有一個功能全面的生成器,可以自動化您的日誌記錄變數,以及更多其他功能 [官網連結](https://www.projectlombok.org/) # 使用 ## 新增maven依賴 ```java org.projectlombok
lombok 1.18.16 provided
``` **注意:** 在這裡 `scope` 要設定為 `provided`, 防止依賴傳遞給其他專案 ## 安裝外掛(可選) 在開發過程中,一般還需要配合外掛使用,在 IDEA 中需要安裝 `Lombok` 外掛即可 為什麼要安裝外掛? 首先在不安裝外掛的情況下,程式碼是可以正常的編譯和執行的。如果不安裝外掛,IDEA 不會自動提示 Lombok 在編譯時才會生成的一些樣板方法,同樣 IDEA 在校驗語法正確性的時候也會提示有問題,會有大面積報紅的程式碼 ## 示例 下面舉兩個栗子,看看使用 lombok 和不使用的區別 建立一個使用者類 **不使用 Lombok** ```java public class User { private Integer id; private Integer age; private String realName; public User() { } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } User user = (User) o; if (!Objects.equals(id, user.id)) { return false; } if (!Objects.equals(age, user.age)) { return false; } return Objects.equals(realName, user.realName); } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (age != null ? age.hashCode() : 0); result = 31 * result + (realName != null ? realName.hashCode() : 0); return result; } @Override public String toString() { return "User{" + "id=" + id + ", age=" + age + ", realName='" + realName + '\'' + '}'; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } } ``` **使用Lombok** ```java @Data public class User { private Integer id; private String username; private Integer age; } ``` 使用 `@Data` 註解會在編譯的時候自動生成以下模板程式碼: - toString - equals - hashCode - getter 不會對 final 屬性生成 - setter 不會對 final 屬性生成 - 必要引數的構造器 關於什麼是必要引數下面會舉例說明 ## 全部註解 上面已經簡單看了一下 `@Data` 註解,下面看下所有的可以用的註解 - **@NonNull** 註解在欄位和構造器的引數上。註解在欄位上,則在 setter, constructor 方法中加入判空,注意這裡需要配合 @Setter、@RequiredArgsConstructor、@AllArgsConstructor 使用;註解在構造器方法引數上,則在構造的時候加入判空 - **@Cleanup** 註解在本地變數上。負責清理資源,當方法直接結束時,會呼叫 close 方法 - **@Setter** 註解在類或欄位。註解在類時為所有欄位生成setter方法,註解在欄位上時只為該欄位生成setter方法,同時可以指定生成的 setter 方法的訪問級別 - **@Getter** 使用方法同 @Setter,區別在於生成的是 getter 方法 - **@ToString** 註解在類上。新增toString方法 - **@EqualsAndHashCode** 註解在類。生成hashCode和equals方法 - **@NoArgsConstructor** 註解在類。生成無參的構造方法。 - **@RequiredArgsConstructor** 註解在類。為類中需要特殊處理的欄位生成構造方法,比如 final 和被 @NonNull 註解的欄位。 - **@AllArgsConstructor** 註解在類,生成包含類中所有欄位的構造方法。 - **@Data** 註解在類,生成setter/getter、equals、canEqual、hashCode、toString方法,如為final屬性,則不會為該屬性生成setter方法。 - **@Value** 註解在類和屬性上。如果註解在類上在類例項建立後不可修改,即不會生成 setter 方法,這個會導致 `@Setter` 不起作用 - **@Builder** 註解在類上,生成構造器 - **@SneakyThrows** - **@Synchronized** 註解在方法上,生成同步方法 - **@With** - 日誌相關: 註解在類,生成 log 常量,類似 private static final xxx log - **@Log** java.util.logging.Logger - **@CommonsLog** org.apache.commons.logging.Log - **@Flogger** com.google.common.flogger.FluentLogger - **@JBossLog** org.jboss.logging.Logger - **@Log4j** org.apache.log4j.Logger - **@Log4j2** org.apache.logging.log4j.Logger - **@Slf4j** org.slf4j.Logger - **@XSlf4j** org.slf4j.ext.XLogger 關於所有的註解可以檢視 https://projectlombok.org/features/all ## 綜合例項 ### 綜合例項一 ```java import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.ToString; @Getter // 生成 getter @AllArgsConstructor // 生成所有的引數 @RequiredArgsConstructor // 生成必要引數的構造器 @ToString // 生成 toString @EqualsAndHashCode // 生成 equals 和 hashCode @Builder // 生成一個 builder public class UserLombok { // 建立 setter 並且校驗 id 不能為空 @Setter @NonNull private Integer id; // 建立 setter 且生成方法的訪問級別為 PROTECTED @Setter(AccessLevel.PROTECTED) private Integer age; // 建立 setter 不校驗是否為空 @Setter private String realName; // 構造器,校驗 id 不能為空 public UserLombok(@NonNull Integer id, Integer age) { this.id = id; this.age = age; } /** * 自定義 realName 的 setter 方法,這個優先高於 Lombok * @param realName 真實姓名 */ public void setRealName(String realName) { this.realName = "realName:" + realName; } } ``` 具體生成的類為 ```java import lombok.NonNull; public class UserLombok { @NonNull private Integer id; private Integer age; private String realName; public UserLombok(@NonNull Integer id, Integer age) { if (id == null) { throw new NullPointerException("id is marked non-null but is null"); } else { this.id = id; this.age = age; } } public void setRealName(String realName) { this.realName = "realName:" + realName; } public static UserLombok.UserLombokBuilder builder() { return new UserLombok.UserLombokBuilder(); } @NonNull public Integer getId() { return this.id; } public Integer getAge() { return this.age; } public String getRealName() { return this.realName; } public UserLombok(@NonNull Integer id, Integer age, String realName) { if (id == null) { throw new NullPointerException("id is marked non-null but is null"); } else { this.id = id; this.age = age; this.realName = realName; } } public UserLombok(@NonNull Integer id) { if (id == null) { throw new NullPointerException("id is marked non-null but is null"); } else { this.id = id; } } public String toString() { return "UserLombok(id=" + this.getId() + ", age=" + this.getAge() + ", realName=" + this.getRealName() + ")"; } public boolean equals(Object o) { if (o == this) { return true; } else if (!(o instanceof UserLombok)) { return false; } else { UserLombok other = (UserLombok)o; if (!other.canEqual(this)) { return false; } else { label47: { Object this$id = this.getId(); Object other$id = other.getId(); if (this$id == null) { if (other$id == null) { break label47; } } else if (this$id.equals(other$id)) { break label47; } return false; } Object this$age = this.getAge(); Object other$age = other.getAge(); if (this$age == null) { if (other$age != null) { return false; } } else if (!this$age.equals(other$age)) { return false; } Object this$realName = this.getRealName(); Object other$realName = other.getRealName(); if (this$realName == null) { if (other$realName != null) { return false; } } else if (!this$realName.equals(other$realName)) { return false; } return true; } } } protected boolean canEqual(Object other) { return other instanceof UserLombok; } public int hashCode() { int PRIME = true; int result = 1; Object $id = this.getId(); int result = result * 59 + ($id == null ? 43 : $id.hashCode()); Object $age = this.getAge(); result = result * 59 + ($age == null ? 43 : $age.hashCode()); Object $realName = this.getRealName(); result = result * 59 + ($realName == null ? 43 : $realName.hashCode()); return result; } public void setId(@NonNull Integer id) { if (id == null) { throw new NullPointerException("id is marked non-null but is null"); } else { this.id = id; } } protected void setAge(Integer age) { this.age = age; } public static class UserLombokBuilder { private Integer id; private Integer age; private String realName; UserLombokBuilder() { } public UserLombok.UserLombokBuilder id(@NonNull Integer id) { if (id == null) { throw new NullPointerException("id is marked non-null but is null"); } else { this.id = id; return this; } } public UserLombok.UserLombokBuilder age(Integer age) { this.age = age; return this; } public UserLombok.UserLombokBuilder realName(String realName) { this.realName = realName; return this; } public UserLombok build() { return new UserLombok(this.id, this.age, this.realName); } public String toString() { return "UserLombok.UserLombokBuilder(id=" + this.id + ", age=" + this.age + ", realName=" + this.realName + ")"; } } } ``` ### 綜合例項二 ```java @Value public class UserLombok { @NonNull private Integer id; // 這裡的 setter 不會生成,所有沒用,這裡反面示例 @Setter(AccessLevel.PROTECTED) private Integer age; private String realName; } ``` `@Value` 是 `ToString、EqualsAndHashCode、AllArgsConstructor、Getter` 的組合註解 生成的程式碼 ```java import lombok.NonNull; public final class UserLombok { @NonNull private final Integer id; private final Integer age; private final String realName; public UserLombok(@NonNull Integer id, Integer age, String realName) { if (id == null) { throw new NullPointerException("id is marked non-null but is null"); } else { this.id = id; this.age = age; this.realName = realName; } } @NonNull public Integer getId() { return this.id; } public Integer getAge() { return this.age; } public String getRealName() { return this.realName; } public boolean equals(Object o) { if (o == this) { return true; } else if (!(o instanceof UserLombok)) { return false; } else { UserLombok other; label44: { other = (UserLombok)o; Object this$id = this.getId(); Object other$id = other.getId(); if (this$id == null) { if (other$id == null) { break label44; } } else if (this$id.equals(other$id)) { break label44; } return false; } Object this$age = this.getAge(); Object other$age = other.getAge(); if (this$age == null) { if (other$age != null) { return false; } } else if (!this$age.equals(other$age)) { return false; } Object this$realName = this.getRealName(); Object other$realName = other.getRealName(); if (this$realName == null) { if (other$realName != null) { return false; } } else if (!this$realName.equals(other$realName)) { return false; } return true; } } public int hashCode() { int PRIME = true; int result = 1; Object $id = this.getId(); int result = result * 59 + ($id == null ? 43 : $id.hashCode()); Object $age = this.getAge(); result = result * 59 + ($age == null ? 43 : $age.hashCode()); Object $realName = this.getRealName(); result = result * 59 + ($realName == null ? 43 : $realName.hashCode()); return result; } public String toString() { return "UserLombok(id=" + this.getId() + ", age=" + this.getAge() + ", realName=" + this.getRealName() + ")"; } } ``` ### 綜合例項三 日誌使用 ```java import lombok.extern.java.Log; @Log public class LogLombok { public void log() { log.info("打個日誌"); } } ``` 生成後代碼 ```java import java.util.logging.Logger; public class LogLombok { private static final Logger log = Logger.getLogger(LogLombok.class.getName()); public LogLombok() { } public void log() { log.info("打個日誌"); } } ``` 通過上面的示例,我們可以看出 Lombok 可以大大簡化我們的程式碼 # Lombok的優缺點 **優點:** 1. 提高開發效率,自動生成getter/setter、toString、builder 等,尤其是類不斷改變過程中,如果使用 IDEA 自動生成的程式碼,我們則需要不停的刪除、重新生成,使用 Lombok 則自動幫助我們完成 2. 讓程式碼變得簡潔,不用過多的去關注相應的模板方法,其中 getter/setter、toString、builder 均為模板程式碼,寫著難受,不寫還不行,而且在 java 14 已經開始計劃支援 `record`, 也在幫我們從原生方面解決這種模板程式碼 3. 屬性做修改時,也簡化了維護為這些屬性所生成的getter/setter方法等 **缺點:** 1. 不同開發人員同時開發同一個使用 Lombok 專案、需要安裝 Lombok 外掛 2. 不利於重構屬性名稱,對應的 setter、getter、builder, IDEA 無法幫助自動重構 3. 有可能降低了原始碼的可讀性和完整性,降低了閱讀原始碼的舒適度,誰會去閱讀模板程式碼呢 ## 解決編譯時出錯問題 編譯時出錯,可能是沒有啟用註解處理器。`Build, Execution, Deployment >
Annotation Processors > Enable annotation processing`。設定完成之後程式正常執行。 # 避坑指南 - 儘量不要使用 `@Data` 註解, 這個註解太全了,不利於維護,除非你知道你在幹什麼 - Java 預設機制如果有其他構造器,則不會生成無參構造器,在使用 `@AllArgsConstructor` 註解時,記得加上 `@NoArgsConstructor` - 如果類定義還在變化階段,不建議使用 `@AllArgsConstructor` 註解 - `@Setter`、`@Getter` 註解如果需要可以縮小使用範圍 - `@ToString` 註解預設不會生成父類的資訊,如果需要生成需要 `@ToString(callSuper = true)` - `@RequiredArgsConstructor` 和 `@NoArgsConstructor` 儘量不要一起使用,無參構造器無法處理 `@NonNull`,但在序列化/反序列化的還是需要提供無參的 - 當團隊決定不再使用 Lombok 的時候,可以使用 Lombok 外掛的 Delombok 一鍵去除,在 `Refactor >
Delombok` 中 **再次注意**- `@AllArgsConstructor` 儘量不要使用 # 參考 - https://projectlombok.org - https://github.com/rzwitserloot/lombok # Lombok工作原理 > 工作原理來自網上資料 在Lombok使用的過程中,只需要新增相應的註解,無需再為此寫任何程式碼。自動生成的程式碼到底是如何產生的呢? 核心之處就是對於註解的解析上。JDK5引入了註解的同時,也提供了兩種解析方式。 - 執行時解析 執行時能夠解析的註解,必須將@Retention設定為RUNTIME,這樣就可以通過反射拿到該註解。java.lang.reflect反射包中提供了一個介面AnnotatedElement,該介面定義了獲取註解資訊的幾個方法,Class、Constructor、Field、Method、Package等都實現了該介面,對反射熟悉的朋友應該都會很熟悉這種解析方式。 - 編譯時解析 編譯時解析有兩種機制,分別簡單描述下: 1)Annotation Processing Tool apt自JDK5產生,JDK7已標記為過期,不推薦使用,JDK8中已徹底刪除,自JDK6開始,可以使用Pluggable Annotation Processing API來替換它,apt被替換主要有2點原因: - api都在com.sun.mirror非標準包下 - 沒有整合到javac中,需要額外執行 2)Pluggable Annotation Processing API [JSR 269](https://jcp.org/en/jsr/detail?id=269)自JDK6加入,作為apt的替代方案,它解決了apt的兩個問題,javac在執行的時候會呼叫實現了該API的程式,這樣我們就可以對編譯器做一些增強,javac執行的過程如下: Lombok本質上就是一個實現了“[JSR 269 API](https://www.jcp.org/en/jsr/detail?id=269)”的程式。在使用javac的過程中,它產生作用的具體流程如下: 1. javac對原始碼進行分析,生成了一棵抽象語法樹(AST) 2. 執行過程中呼叫實現了“JSR 269 API”的Lombok程式 3. 此時Lombok就對第一步驟得到的AST進行處理,找到@Data註解所在類對應的語法樹(AST),然後修改該語法樹(AST),增加getter和setter方法定義的相應樹節點 4. javac使用修改後的抽象語法樹(AST)生成位元組碼檔案,即給class增加新的節點(程式碼塊) 通過讀Lombok原始碼,發現對應註解的實現都在HandleXXX中,比如@Getter註解的實現在HandleGetter.handle()。還有一些其它類庫使用這種方式實現,比如[Google Auto](https://github.com/google/auto)、[Dagger](http://square.github.io/dagger/)等等。 ![白色兔子公眾號圖片](https://img2020.cnblogs.com/blog/1246875/202008/1246875-20200822203040972-1191312