什麼是Lombok
Lombok是一款Java開發插件,可以通過它定義的註解來精簡冗長和繁瑣的代碼,主要針對簡單的Java模型對象(POJO)。
好處就顯而易見了,可以節省大量重複工作,特別是當POJO類的屬性增減時,需要重複修改的Getter/Setter、構造器方法、equals方法和toString方法等。
而且Lombok針對這些內容的處理是在編譯期,而不是通過反射機制,這樣的好處是並不會降低系統的性能。
下面我們就看看具體的使用。
Lombok的安裝
Lombok的安裝分兩部分:Idea插件的安裝和maven中pom文件的導入。
第一步,在Idea的插件配置中搜索Lombok或官網下載本地安裝。
同時,在插件的描述中也能夠看到它支持的註解。
第二步,引入pom中依賴,當前最細版本1.18.10。
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.10</version>
</dependency>
如果是通過Idea創建Spring Boot項目,可在創建項目時直接在“Developer Tool”中選擇Lombok。
完成了以上兩步,就可以在代碼中使用該款神器了。
Lombok的使用
@Data
@Data最常用的註解之一。註解在類上,提供該類所有屬性的getter/setter方法,還提供了equals、canEqual、hashCode、toString方法。
這裏的提供什麼意思?就是開發人員不用手寫相應的方法,而Lombok會幫你生成。
使用@Data示例如下,最直觀的就是不用寫getter/setter方法。
@Data
public class Demo {
private int id;
private String remark;
}
我們看該類編譯之後是什麼樣子。
public class Demo { private int id; private String remark;
public Demo() { } public int getId() { return this.id; } public String getRemark() { return this.remark; } public void setId(final int id) { this.id = id; } public void setRemark(final String remark) { this.remark = remark; } public boolean equals(final Object o) { if (o == this) { return true; } else if (!(o instanceof Demo)) { return false; } else { Demo other = (Demo)o; if (!other.canEqual(this)) { return false; } else if (this.getId() != other.getId()) { return false; } else { Object this$remark = this.getRemark(); Object other$remark = other.getRemark(); if (this$remark == null) { if (other$remark != null) { return false; } } else if (!this$remark.equals(other$remark)) { return false; } return true; } } } protected boolean canEqual(final Object other) { return other instanceof Demo; } public int hashCode() { int PRIME = true; int result = 1; int result = result * 59 this.getId(); Object $remark = this.getRemark(); result = result * 59 ($remark == null ? 43 : $remark.hashCode()); return result; } public String toString() { return "Demo(id=" this.getId() ", remark=" this.getRemark() ")"; }
}
上面的反編譯代碼,我們可以看到提供了默認的構造方法、屬性的getter/setter方法、equals、canEqual、hashCode、toString方法。
使用起來是不是很方便,最關鍵的是,當新增屬性或減少屬性時,直接刪除屬性定義即可,效率是否提升了很多?
爲了節省篇幅,後面相關注解我們就不再看反編譯的效果了,大家使用idea直接打開編譯之後對應的.class文件即可看到。
@Setter
作用於屬性上,爲該屬性提供setter方法; 作用與類上,爲該類所有的屬性提供setter方法, 都提供默認構造方法。
public class Demo {
private int id;
@Setter
private String remark;
}
@Setter
public class Demo {
private int id;
private String remark;
}
@Getter
基本使用同@Setter方法,不過提供的是getter方法,不再贅述。
@Log4j
作用於類上,爲該類提供一個屬性名爲log的log4j日誌對象。
@Log4j
public class Demo {
}
該屬性一般使用於Controller、Service等業務處理類上。與此註解相同的還有@Log4j2,顧名思義,針對Log4j2。
@AllArgsConstructor
作用於類上,爲該類提供一個包含全部參的構造方法,注意此時默認構造方法不會提供。
@AllArgsConstructor
public class Demo {
private int id;
private String remark;
}
效果如下:
public class Demo { private int id; private String remark;
public Demo(final int id, final String remark) { this.id = id; this.remark = remark; }
}
@NoArgsConstructor
作用於類上,提供一個無參的構造方法。可以和@AllArgsConstructor同時使用,此時會生成兩個構造方法:無參構造方法和全參構造方法。
@EqualsAndHashCode
作用於類上,生成equals、canEqual、hashCode方法。具體效果參看最開始的@Data效果。
@NonNull
作用於屬性上,提供關於此參數的非空檢查,如果參數爲空,則拋出空指針異常。
使用方法:
public class Demo {
@NonNull
private int id;
private String remark;
}
效果如下:
public class Demo {
@NonNull
private int id;
private String remark;
}
@RequiredArgsConstructor
作用於類上,由類中所有帶有@NonNull註解或者帶有final修飾的成員變量作爲參數生成構造方法。
@Cleanup
作用於變量,保證該變量代表的資源會被自動關閉,默認調用資源的close()方法,如果該資源有其它關閉方法,可使用@Cleanup(“methodName”)來指定。
public void jedisExample(String[] args) {
try {
@Cleanup Jedis jedis = redisService.getJedis();
} catch (Exception ex) {
logger.error(“Jedis異常:”,ex)
}
}
效果相當於:
public void jedisExample(String[] args) {
Jedis jedis= null; try { jedis = redisService.getJedis(); } catch (Exception e) { logger.error(“Jedis異常:”,ex) } finally { if (jedis != null) { try { jedis.close(); } catch (Exception e) { e.printStackTrace(); } } }
}
@ToString
作用於類上,生成包含所有參數的toString方法。見@Data中toString方法。
@Value
作用於類上,會生成全參數的構造方法、getter方法、equals、hashCode、toString方法。與@Data相比多了全參構造方法,少了默認構造方法、setter方法和canEqual方法。
該註解需要注意的是:會將字段添加上final修飾,個人感覺此處有些失控,不太建議使用。
@SneakyThrows
作用於方法上,相當於把方法內的代碼添加了一個try-catch處理,捕獲異常catch中用Lombok.sneakyThrow(e)拋出異常。使用@SneakyThrows(BizException.class)指定拋出具體異常。
@SneakyThrows
public int getValue(){
int a = 1;
int b = 0;
return a/b;
}
效果如下:
public int getValue() {
try {
int a = 1;
int b = 0;
return a / b;
} catch (Throwable var3) {
throw var3;
}
}
@Synchronized
作用於類方法或實例方法上,效果與synchronized相同。區別在於鎖對象不同,對於類方法和實例方法,synchronized關鍵字的鎖對象分別是類的class對象和this對象,而@Synchronized的鎖對象分別是私有靜態final對象lock和私有final對象lock。也可以指定鎖對象。
public class FooExample {
private final Object readLock = new Object();
@Synchronized
public static void hello() {
System.out.println(“world”);
}
@Synchronized(“readLock”)
public void foo() {
System.out.println(“bar”);
}
}
效果相當於如下:
public class FooExample {
private static final Object $LOCK = new Object[0];
private final Object readLock = new Object();
public static void hello() {
synchronized($LOCK) {
System.out.println(“world”);
}
}
public void foo() {
synchronized(readLock) {
System.out.println(“bar”);
}
}
}
val
使用val作爲局部變量聲明的類型,而不是實際寫入類型。 執行此操作時,將從初始化表達式推斷出類型。
public Map<String, String> getMap() {
val map = new HashMap<String, String>();
map.put("1", "a");
return map;
}
效果如下:
public Map<String, String> getMap() {
HashMap<String, String> map = new HashMap();
map.put("1", "a");
return map;
}
也就是說在局部變量中,Lombok幫你推斷出具體的類型,但只能用於局部變量中。
@Builder
作用於類上,如果你喜歡使用Builder的流式操作,那麼@Builder可能是你喜歡的註解了。
使用方法:
@Builder
public class Demo {
private int id;
private String remark;
}
效果如下:
public class Demo { private int id; private String remark;
Demo(final int id, final String remark) { this.id = id; this.remark = remark; } public static Demo.DemoBuilder builder() { return new Demo.DemoBuilder(); } public static class DemoBuilder { private int id; private String remark; DemoBuilder() { } public Demo.DemoBuilder id(final int id) { this.id = id; return this; } public Demo.DemoBuilder remark(final String remark) { this.remark = remark; return this; } public Demo build() { return new Demo(this.id, this.remark); } public String toString() { return "Demo.DemoBuilder(id=" this.id ", remark=" this.remark ")"; } }
}
我們可以看到,在該類內部提供了DemoBuilder類用來處理具體的流式操作。同時提供了全參的構造方法。
小結
最後,說一下個人的看法,此神器雖然好用,但也不建議大家無條件的使用,爲了程序的效率等問題,該自己親手寫的代碼還是要自己親手寫。畢竟,只有定製化的才能達到最優化和最符合當前場景。