本文介紹了SpringBoot優雅編碼之Lombok加持,分享給大家,具體如下:
概述
Lombok 通過提供簡單的語法註解形式來幫助簡化消除一些必須有但顯得很臃腫的java 代碼。典型的是對於POJO對象的簡化(如自動幫我們生成Setter和Getter等),有了Lombok的加持,開發人員可以免去很多重複且臃腫的操作,極大地提高java代碼的信噪比,因此我們必須嘗試並應用起來!
IntelliJ IDEA上配置
方法一:直接在IDEA界面中配置
首先進入Plugins界面:
然後搜索並安裝Lombok插件:
最後不要忘了開啟Annotation Processors的Enable選項:
上述安裝完成以後需要重啟IDEA生效!
方法二:手動下載Lombok插件安裝
有時由於網絡原因,上面方法一這種方式安裝失敗,因此只能手動下載安裝
下載lombok插件:
https://github.com/mplushnikov/lombok-intellij-plugin/releases
Plugins -> Install plugin from disk... 選擇下載的zip包安裝
重啟idea即可
IDE中設置完成以後需要在pom.xml中添加如下所示的lombok依賴才能使用
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.16</version></dependency>
Lombok主要註解
@Getter and @Setter / 自動為屬性提供Set和Get 方法@ToString / 該註解的作用是為類自動生成toString()方法@EqualsAndHashCode / 為對象字段自動生成hashCode和equals實現@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor / 顧名思義,為類自動生成對應參數的constructor@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog / 自動為類添加對應的log支持@Data / 自動為所有字段添加@ToString, @EqualsAndHashCode, @Getter,為非final字段添加@Setter,和@RequiredArgsConstructor,本質上相當於幾個註解的綜合效果@NonNull / 自動幫助我們避免空指針。作用在方法參數上的註解,用於自動生成空值參數檢查@Cleanup / 自動幫我們調用close()方法。作用在局部變量上,在作用域結束時會自動調用close方法釋放資源下文就Lombok中用的最為頻繁的@Data和@Log註解進行代碼實戰!
@Data註解使用
官網關於@Data註解的解釋如下:
All together now: A shortcut for @ToString, @EqualsAndHashCode, @Getter on all fields, @Setter on all non-final fields, and @RequiredArgsConstructor!
不難理解,其可以看成是多個Lombok註解的集成,因此使用很方便!
先來創建一個POJO實體UserLombok,普通的寫法如下:
public class UserLombok { private final String name; private int age; private double score; private String[] tags; public UserLombok(String name) { this.name = name; } public String getName() { return this.name; } void setAge(int age) { this.age = age; } public int getAge() { return this.age; } public void setScore(double score) { this.score = score; } public double getScore() { return this.score; } public String[] getTags() { return this.tags; } public void setTags(String[] tags) { this.tags = tags; } @Override public String toString() { return "DataExample(" + this.getName() + ", " + this.getAge() + ", " + this.getScore() + ", " + Arrays.deepToString(this.getTags()) + “)”; } protected boolean canEqual(Object other) { return other instanceof DataExample; } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof DataExample)) return false; DataExample other = (DataExample) o; if (!other.canEqual((Object)this)) return false; if (this.getName() == null ? other.getName() != null : !this.getName().equals(other.getName())) return false; if (this.getAge() != other.getAge()) return false; if (Double.compare(this.getScore(), other.getScore()) != 0) return false; if (!Arrays.deepEquals(this.getTags(), other.getTags())) return false; return true; } @Override public int hashCode() { final int PRIME = 59; int result = 1; final long temp1 = Double.doubleToLongBits(this.getScore()); result = (result*PRIME) + (this.getName() == null ? 43 : this.getName().hashCode()); result = (result*PRIME) + this.getAge(); result = (result*PRIME) + (int)(temp1 ^ (temp1 >>> 32)); result = (result*PRIME) + Arrays.deepHashCode(this.getTags()); return result; }}Lombok加持後,寫法可簡化為:
@Datapublic class UserLombok { private final String name; private int age; private double score; private String[] tags;}在IDEA中使用時,Lombok的註解會自動補全,如下圖所示:
我們來寫POJO的測試代碼
public static void main( String[] args ) { UserLombok userLombok = new UserLombok("hansonwang99”); userLombok.setAge(18); String[] array = new String[]{"apple","juice”}; userLombok.setTags( array ); userLombok.setScore( 99.0 ); System.out.println(userLombok); }由下圖我們可以看到IDEA依然可以自動為我們補全由Lombok自動生成的代碼:
結果打印
由於Lombok為我們自動生成了toString方法,因此對象的打印結果如下:
UserLombok(name=hansonwang99, age=18, score=99.0, tags=[apple, juice])
@Log註解實戰
在我的文章Spring Boot日誌框架實踐一文中,我們使用Log4j2來作為日誌對象,其寫法如下:
@RestController@RequestMapping("/testlogging”)public class LoggingTestController { private final Logger logger = LogManager.getLogger(this.getClass()); @GetMapping("/hello”) public String hello() { for(int i=0;i<10_0000;i++){ logger.info("info execute index method”); logger.warn("warn execute index method”); logger.error("error execute index method”); } return "My First SpringBoot Application”; }}若改用Lombok後,寫法變得更加簡潔,我們只需要引入對應的@Log註解即可完成log對象的生成:
@RestController@RequestMapping("/testloggingwithlombok”)@Log4j2public class LoggingTestControllerLombok { @GetMapping("/hello”) public String hello() { for(int i=0;i<10_0000;i++){ log.info("info execute index method”); log.warn("warn execute index method”); log.error("error execute index method”); } return "My First SpringBoot Application”; }}怎麼樣,是不是一切都是那麼地優雅!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。