Lombok简介、使用、工作原理、优缺点

Lombok 项目是一个 Java 库,它会自动插入编辑器和构建工具中,Lombok 提供了一组有用的注解,用来消除 Java 类中的大量样板代码。



简介

官方介绍

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 方法,带有一个注释的您的类有一个功能全面的生成器,可以自动化您的日志记录变量,以及更多其他功能

官网链接

使用

添加maven依赖

  1. <dependency>
  2. <groupId>org.projectlombok</groupId>
  3. <artifactId>lombok</artifactId>
  4. <version>1.18.16</version>
  5. <scope>provided</scope>
  6. </dependency>

注意: 在这里 scope 要设置为 provided, 防止依赖传递给其他项目

安装插件(可选)

在开发过程中,一般还需要配合插件使用,在 IDEA 中需要安装 Lombok 插件即可

为什么要安装插件?

首先在不安装插件的情况下,代码是可以正常的编译和运行的。如果不安装插件,IDEA 不会自动提示 Lombok 在编译时才会生成的一些样板方法,同样 IDEA 在校验语法正确性的时候也会提示有问题,会有大面积报红的代码

示例

下面举两个栗子,看看使用 lombok 和不使用的区别

创建一个用户类

不使用 Lombok

  1. public class User {
  2. private Integer id;
  3. private Integer age;
  4. private String realName;
  5. public User() {
  6. }
  7. @Override
  8. public boolean equals(Object o) {
  9. if (this == o) {
  10. return true;
  11. }
  12. if (o == null || getClass() != o.getClass()) {
  13. return false;
  14. }
  15. User user = (User) o;
  16. if (!Objects.equals(id, user.id)) {
  17. return false;
  18. }
  19. if (!Objects.equals(age, user.age)) {
  20. return false;
  21. }
  22. return Objects.equals(realName, user.realName);
  23. }
  24. @Override
  25. public int hashCode() {
  26. int result = id != null ? id.hashCode() : 0;
  27. result = 31 * result + (age != null ? age.hashCode() : 0);
  28. result = 31 * result + (realName != null ? realName.hashCode() : 0);
  29. return result;
  30. }
  31. @Override
  32. public String toString() {
  33. return "User{" +
  34. "id=" + id +
  35. ", age=" + age +
  36. ", realName='" + realName + '\'' +
  37. '}';
  38. }
  39. public Integer getId() {
  40. return id;
  41. }
  42. public void setId(Integer id) {
  43. this.id = id;
  44. }
  45. public Integer getAge() {
  46. return age;
  47. }
  48. public void setAge(Integer age) {
  49. this.age = age;
  50. }
  51. public String getRealName() {
  52. return realName;
  53. }
  54. public void setRealName(String realName) {
  55. this.realName = realName;
  56. }
  57. }

使用Lombok

  1. @Data
  2. public class User {
  3. private Integer id;
  4. private String username;
  5. private Integer age;
  6. }

使用 @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

综合实例

综合实例一

  1. import lombok.AccessLevel;
  2. import lombok.AllArgsConstructor;
  3. import lombok.Builder;
  4. import lombok.EqualsAndHashCode;
  5. import lombok.Getter;
  6. import lombok.NonNull;
  7. import lombok.RequiredArgsConstructor;
  8. import lombok.Setter;
  9. import lombok.ToString;
  10. @Getter // 生成 getter
  11. @AllArgsConstructor // 生成所有的参数
  12. @RequiredArgsConstructor // 生成必要参数的构造器
  13. @ToString // 生成 toString
  14. @EqualsAndHashCode // 生成 equals 和 hashCode
  15. @Builder // 生成一个 builder
  16. public class UserLombok {
  17. // 创建 setter 并且校验 id 不能为空
  18. @Setter
  19. @NonNull
  20. private Integer id;
  21. // 创建 setter 且生成方法的访问级别为 PROTECTED
  22. @Setter(AccessLevel.PROTECTED)
  23. private Integer age;
  24. // 创建 setter 不校验是否为空
  25. @Setter
  26. private String realName;
  27. // 构造器,校验 id 不能为空
  28. public UserLombok(@NonNull Integer id, Integer age) {
  29. this.id = id;
  30. this.age = age;
  31. }
  32. /**
  33. * 自定义 realName 的 setter 方法,这个优先高于 Lombok
  34. * @param realName 真实姓名
  35. */
  36. public void setRealName(String realName) {
  37. this.realName = "realName:" + realName;
  38. }
  39. }

具体生成的类为

  1. import lombok.NonNull;
  2. public class UserLombok {
  3. @NonNull
  4. private Integer id;
  5. private Integer age;
  6. private String realName;
  7. public UserLombok(@NonNull Integer id, Integer age) {
  8. if (id == null) {
  9. throw new NullPointerException("id is marked non-null but is null");
  10. } else {
  11. this.id = id;
  12. this.age = age;
  13. }
  14. }
  15. public void setRealName(String realName) {
  16. this.realName = "realName:" + realName;
  17. }
  18. public static UserLombok.UserLombokBuilder builder() {
  19. return new UserLombok.UserLombokBuilder();
  20. }
  21. @NonNull
  22. public Integer getId() {
  23. return this.id;
  24. }
  25. public Integer getAge() {
  26. return this.age;
  27. }
  28. public String getRealName() {
  29. return this.realName;
  30. }
  31. public UserLombok(@NonNull Integer id, Integer age, String realName) {
  32. if (id == null) {
  33. throw new NullPointerException("id is marked non-null but is null");
  34. } else {
  35. this.id = id;
  36. this.age = age;
  37. this.realName = realName;
  38. }
  39. }
  40. public UserLombok(@NonNull Integer id) {
  41. if (id == null) {
  42. throw new NullPointerException("id is marked non-null but is null");
  43. } else {
  44. this.id = id;
  45. }
  46. }
  47. public String toString() {
  48. return "UserLombok(id=" + this.getId() + ", age=" + this.getAge() + ", realName=" + this.getRealName() + ")";
  49. }
  50. public boolean equals(Object o) {
  51. if (o == this) {
  52. return true;
  53. } else if (!(o instanceof UserLombok)) {
  54. return false;
  55. } else {
  56. UserLombok other = (UserLombok)o;
  57. if (!other.canEqual(this)) {
  58. return false;
  59. } else {
  60. label47: {
  61. Object this$id = this.getId();
  62. Object other$id = other.getId();
  63. if (this$id == null) {
  64. if (other$id == null) {
  65. break label47;
  66. }
  67. } else if (this$id.equals(other$id)) {
  68. break label47;
  69. }
  70. return false;
  71. }
  72. Object this$age = this.getAge();
  73. Object other$age = other.getAge();
  74. if (this$age == null) {
  75. if (other$age != null) {
  76. return false;
  77. }
  78. } else if (!this$age.equals(other$age)) {
  79. return false;
  80. }
  81. Object this$realName = this.getRealName();
  82. Object other$realName = other.getRealName();
  83. if (this$realName == null) {
  84. if (other$realName != null) {
  85. return false;
  86. }
  87. } else if (!this$realName.equals(other$realName)) {
  88. return false;
  89. }
  90. return true;
  91. }
  92. }
  93. }
  94. protected boolean canEqual(Object other) {
  95. return other instanceof UserLombok;
  96. }
  97. public int hashCode() {
  98. int PRIME = true;
  99. int result = 1;
  100. Object $id = this.getId();
  101. int result = result * 59 + ($id == null ? 43 : $id.hashCode());
  102. Object $age = this.getAge();
  103. result = result * 59 + ($age == null ? 43 : $age.hashCode());
  104. Object $realName = this.getRealName();
  105. result = result * 59 + ($realName == null ? 43 : $realName.hashCode());
  106. return result;
  107. }
  108. public void setId(@NonNull Integer id) {
  109. if (id == null) {
  110. throw new NullPointerException("id is marked non-null but is null");
  111. } else {
  112. this.id = id;
  113. }
  114. }
  115. protected void setAge(Integer age) {
  116. this.age = age;
  117. }
  118. public static class UserLombokBuilder {
  119. private Integer id;
  120. private Integer age;
  121. private String realName;
  122. UserLombokBuilder() {
  123. }
  124. public UserLombok.UserLombokBuilder id(@NonNull Integer id) {
  125. if (id == null) {
  126. throw new NullPointerException("id is marked non-null but is null");
  127. } else {
  128. this.id = id;
  129. return this;
  130. }
  131. }
  132. public UserLombok.UserLombokBuilder age(Integer age) {
  133. this.age = age;
  134. return this;
  135. }
  136. public UserLombok.UserLombokBuilder realName(String realName) {
  137. this.realName = realName;
  138. return this;
  139. }
  140. public UserLombok build() {
  141. return new UserLombok(this.id, this.age, this.realName);
  142. }
  143. public String toString() {
  144. return "UserLombok.UserLombokBuilder(id=" + this.id + ", age=" + this.age + ", realName=" + this.realName + ")";
  145. }
  146. }
  147. }

综合实例二

  1. @Value
  2. public class UserLombok {
  3. @NonNull
  4. private Integer id;
  5. // 这里的 setter 不会生成,所有没用,这里反面示例
  6. @Setter(AccessLevel.PROTECTED)
  7. private Integer age;
  8. private String realName;
  9. }

@ValueToString、EqualsAndHashCode、AllArgsConstructor、Getter 的组合注解

生成的代码

  1. import lombok.NonNull;
  2. public final class UserLombok {
  3. @NonNull
  4. private final Integer id;
  5. private final Integer age;
  6. private final String realName;
  7. public UserLombok(@NonNull Integer id, Integer age, String realName) {
  8. if (id == null) {
  9. throw new NullPointerException("id is marked non-null but is null");
  10. } else {
  11. this.id = id;
  12. this.age = age;
  13. this.realName = realName;
  14. }
  15. }
  16. @NonNull
  17. public Integer getId() {
  18. return this.id;
  19. }
  20. public Integer getAge() {
  21. return this.age;
  22. }
  23. public String getRealName() {
  24. return this.realName;
  25. }
  26. public boolean equals(Object o) {
  27. if (o == this) {
  28. return true;
  29. } else if (!(o instanceof UserLombok)) {
  30. return false;
  31. } else {
  32. UserLombok other;
  33. label44: {
  34. other = (UserLombok)o;
  35. Object this$id = this.getId();
  36. Object other$id = other.getId();
  37. if (this$id == null) {
  38. if (other$id == null) {
  39. break label44;
  40. }
  41. } else if (this$id.equals(other$id)) {
  42. break label44;
  43. }
  44. return false;
  45. }
  46. Object this$age = this.getAge();
  47. Object other$age = other.getAge();
  48. if (this$age == null) {
  49. if (other$age != null) {
  50. return false;
  51. }
  52. } else if (!this$age.equals(other$age)) {
  53. return false;
  54. }
  55. Object this$realName = this.getRealName();
  56. Object other$realName = other.getRealName();
  57. if (this$realName == null) {
  58. if (other$realName != null) {
  59. return false;
  60. }
  61. } else if (!this$realName.equals(other$realName)) {
  62. return false;
  63. }
  64. return true;
  65. }
  66. }
  67. public int hashCode() {
  68. int PRIME = true;
  69. int result = 1;
  70. Object $id = this.getId();
  71. int result = result * 59 + ($id == null ? 43 : $id.hashCode());
  72. Object $age = this.getAge();
  73. result = result * 59 + ($age == null ? 43 : $age.hashCode());
  74. Object $realName = this.getRealName();
  75. result = result * 59 + ($realName == null ? 43 : $realName.hashCode());
  76. return result;
  77. }
  78. public String toString() {
  79. return "UserLombok(id=" + this.getId() + ", age=" + this.getAge() + ", realName=" + this.getRealName() + ")";
  80. }
  81. }

综合实例三

日志使用

  1. import lombok.extern.java.Log;
  2. @Log
  3. public class LogLombok {
  4. public void log() {
  5. log.info("打个日志");
  6. }
  7. }

生成后代码

  1. import java.util.logging.Logger;
  2. public class LogLombok {
  3. private static final Logger log = Logger.getLogger(LogLombok.class.getName());
  4. public LogLombok() {
  5. }
  6. public void log() {
  7. log.info("打个日志");
  8. }
  9. }

通过上面的示例,我们可以看出 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 尽量不要使用

参考

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自JDK6加入,作为apt的替代方案,它解决了apt的两个问题,javac在执行的时候会调用实现了该API的程序,这样我们就可以对编译器做一些增强,javac执行的过程如下:

Lombok本质上就是一个实现了“JSR 269 API”的程序。在使用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 AutoDagger等等。

今天 1024,为了不 996,Lombok 用起来以及避坑指南的更多相关文章

  1. Lombok好用是好用,就是容易踩坑,这份避坑指南请查收

    序言 各位好啊,我是会编程的蜗牛,作为java开发者,我们平常在开发过程中,总是希望能够尽量少敲代码.这一方面,当然是为了偷懒,另一方面,当然也是为了代码看起来更加简洁一点,不断往编程规范上靠.然后其 ...

  2. fastJson + lombok + 属性名命名 踩坑点

    JavaBean属性名要求:前两个字母要么都大写,要么都小写 package com.jdyh.worker.project.controller; import com.alibaba.fastjs ...

  3. Lombok中@Data注解的坑

    开发遇到@Data注解的大坑 如果使用@Data注解,会默认重写hashcode和equals方法 那会遇到什么问题呢? 比如说: @Data public class DataTest { priv ...

  4. SpringBoot整合log4j2进行日志配置及防坑指南

    写在前面 最近项目经理要求将原先项目中的日志配置logBack,修改为log4j2,据说是log4j2性能更优于logback,具体快多少,网上有说快10多倍,看来还是很快的,于是新的一波挑战又开始了 ...

  5. 【Java分享客栈】SpringBoot整合WebSocket+Stomp搭建群聊项目

    前言 前两周经常有大学生小伙伴私信给我,问我可否有偿提供毕设帮助,我说暂时没有这个打算,因为工作实在太忙,现阶段无法投入到这样的领域内,其中有两个小伙伴又问到我websocket该怎么使用,想给自己的 ...

  6. JetBrains Fleet初体验,如何运行一个java项目

    序言 各位好啊,我是会编程的蜗牛,JetBrains 日前宣布其打造的下一代 IDE Fleet 正式推出公共预览版,现已开放下载.作为java开发者,对于JetBrains开发的全家桶可以说是印象深 ...

  7. 如何用Virtualbox搭建一个虚拟机

    序言 各位好啊,我是会编程的蜗牛,作为java开发者,我们肯定会接触Linux服务器,除了使用云服务搭建Linux服务器外,我们一般也可以在自己的电脑上安装虚拟机来搭建Linux服务器用于各种功能的验 ...

  8. postman一些你不常用的实用技巧,竟然还能这么玩

    序言 各位好啊,我是会编程的蜗牛,作为java开发者,平时调试接口的时候,肯定需要用到接口调试工具,或者Swagger之类的.Swagger的优势在于它可以将后台加的一些接口注释信息直接展示出来,但是 ...

  9. linux中ulimit作用

    一.作用 Linux对于每个用户,系统限制其最大进程数.为提高性能,可以根据设备资源情况,设置各linux 用户的最大进程数. ulimit主要是用来限制进程对资源的使用情况的,它支持各种类型的限制, ...

随机推荐

  1. hystrix源码小贴士之Yammer Publisher

    HystrixYammerMetricsPublisher 继承HystrixMetricsPublisher,创建HystrixYammerMetricsPublisherCommand.Hystr ...

  2. Dubbo工作流程

    一.dubbo整体架构 其中Service 和 Config 层为 API,对应服务提供方来说是使用ServiceConfig来代表一个要发布的服务配置对象,对应服务消费方来说ReferenceCon ...

  3. 【Processing-日常4】等待动画2

    之前在CSDN上发表过: https://blog.csdn.net/fddxsyf123/article/details/79781034

  4. kmt字符串匹配

    # -*- coding:utf-8 -*-class StringPattern: def findAppearance(self, A, lena, B, lenb): pos=0 tmp = 0 ...

  5. tomcat在linux下安装

    1.下载地址: https://tomcat.apache.org/download-90.cgi 2.上传linux 3.查看是否上传成功 4.解压: 5.进入后,查看README.md文件,可以查 ...

  6. 实用向—总结一些唯一ID生成方式

    在日常的项目开发中,我们经常会遇到需要生成唯一ID的业务场景,不同的业务对唯一ID的生成方式与要求都会不尽相同,一是生成方式多种多样,如UUID.雪花算法.数据库递增等:其次业务要求上也各有不同,有的 ...

  7. Windows10下JDK8的下载安装与环境变量的配置

    Windows10下JDK8的下载安装与环境变量的配置 下载JDK8(64位) 链接:https://pan.baidu.com/s/10ZMK7NB68kPORZsPOhivog 提取码:agsa ...

  8. .Net Core 2.2 存取Cookie

    第一步(注释代码):注释Startup.cs中 ConfigureServices 函数中的  options.CheckConsentNeeded = context => true; 第二步 ...

  9. 在KEIL下查看单片机编程内存使用情况

    原文链接:https://blog.csdn.net/D_azzle/article/details/83410141 截至到目前为止,本人接触单片机也有将近一年的时间.这一年以来也接触过了很具代表性 ...

  10. CF149D Coloring Brackets

    CF149D Coloring Brackets Link 题面: 给出一个配对的括号序列(如"\((())()\)"."\(()\)"等, "\() ...