Lombok 安装及使用指南

你的名字 2022-09-09 06:20 106阅读 0赞

简介

为了减少写一些 get/set/toString 方法,让项目代码更加整洁,提高开发效率,发现大家都开始采用 Lombok 这个工具。Lombok 是一个 Java 类库,它会自动插入编辑器和构建工具,用于帮助开发人员消除 Java 中冗长样板代码。而我们开发人员所要做的,仅仅是添加几个 Lombok 中的注解,就可以替换掉原来的多行 get/set/toString 方法代码,既简洁也易于维护。下面我们就来看看,如何安装并使用这一工具。

安装 Lombok

日常开发中,相信大多数人现在使用的都是 IDEA 这个 Java 神器了,如果你还在使用 Eclipse 或者 MyEclipse 等工具,那强烈推荐你去体验一把 IDEA,相信你一用上它就会爱上他它的强大!下面我就一在 IDEA 中使用 Lombok 为例,看看如何安装并使用它。

在先前 IDEA 的版本中,Lombok 是需要通过插件来安装的,安装方法如下:依次进入File -> Settings -> Plugins,然后搜索 Lombok ,最后进行安装即可。而在新版本的 IDEA 中,Lombok 已经被集成到 IDEA 中,我们不用再去安装它就可以直接使用,可以说是十分方便了。

  • 老版本 IDEA 安装 Lombok

bbf68fec0f5f36fd3090597c98897454.png

  • 新版本中集成了 Lombok

76f23e5e53b523179c2d70bb52c56392.png

以上就是 Lombok 的安装过程了,是不是十分简单?那接下来我们就来看看,如何在我们的项目中使用 Lombok!

Lombok 使用

现在大家进行项目管理时用的工具大多应该都是 Maven,所以我们直接在需要使用 Lombok 的项目中加入 Lombok 编译支持,也就是在 pom.xml 文件中加入以下依赖。

  1. <dependency>
  2. <groupId>org.projectlombok</groupId>
  3. <artifactId>lombok</artifactId>
  4. </dependency>

导入相关依赖之后,接下来就是具体使用过程了。

具体使用

在需要的实体类中引入相关注解即可,只不过注解不同它们所对应的功能也不同,而且同一个注解可能在不同位置的功能也不一样。如下图;

1f5d1a24c42a9e069c7588a5f1d7142e.png

常用注解

@Data

注解在 上:给类的所有属性提供 getset 方法,此外还有 equals、canEqual、hashCode、toString 方法以及 默认参数为空的构造方法

  • 使用前

    package com.cunyu.user.entity;

    public class User {

    1. private Long id;
    2. private String name;
    3. private Integer age;
    4. private String email;
    5. public User() {
    6. }
    7. public Long getId() {
    8. return this.id;
    9. }
    10. public String getName() {
    11. return this.name;
    12. }
    13. public Integer getAge() {
    14. return this.age;
    15. }
    16. public String getEmail() {
    17. return this.email;
    18. }
    19. public void setId(final Long id) {
    20. this.id = id;
    21. }
    22. public void setName(final String name) {
    23. this.name = name;
    24. }
    25. public void setAge(final Integer age) {
    26. this.age = age;
    27. }
    28. public void setEmail(final String email) {
    29. this.email = email;
    30. }
    31. public boolean equals(final Object o) {
    32. if (o == this) {
    33. return true;
    34. } else if (!(o instanceof User)) {
    35. return false;
    36. } else {
    37. User other = (User)o;
    38. if (!other.canEqual(this)) {
    39. return false;
    40. } else {
    41. label59: {
    42. Object this$id = this.getId();
    43. Object other$id = other.getId();
    44. if (this$id == null) {
    45. if (other$id == null) {
    46. break label59;
    47. }
    48. } else if (this$id.equals(other$id)) {
    49. break label59;
    50. }
    51. return false;
    52. }
    53. Object this$age = this.getAge();
    54. Object other$age = other.getAge();
    55. if (this$age == null) {
    56. if (other$age != null) {
    57. return false;
    58. }
    59. } else if (!this$age.equals(other$age)) {
    60. return false;
    61. }
    62. Object this$name = this.getName();
    63. Object other$name = other.getName();
    64. if (this$name == null) {
    65. if (other$name != null) {
    66. return false;
    67. }
    68. } else if (!this$name.equals(other$name)) {
    69. return false;
    70. }
    71. Object this$email = this.getEmail();
    72. Object other$email = other.getEmail();
    73. if (this$email == null) {
    74. if (other$email != null) {
    75. return false;
    76. }
    77. } else if (!this$email.equals(other$email)) {
    78. return false;
    79. }
    80. return true;
    81. }
    82. }
    83. }
    84. protected boolean canEqual(final Object other) {
    85. return other instanceof User;
    86. }
    87. public int hashCode() {
    88. int PRIME = true;
    89. int result = 1;
    90. Object $id = this.getId();
    91. int result = result * 59 + ($id == null ? 43 : $id.hashCode());
    92. Object $age = this.getAge();
    93. result = result * 59 + ($age == null ? 43 : $age.hashCode());
    94. Object $name = this.getName();
    95. result = result * 59 + ($name == null ? 43 : $name.hashCode());
    96. Object $email = this.getEmail();
    97. result = result * 59 + ($email == null ? 43 : $email.hashCode());
    98. return result;
    99. }
    100. public String toString() {
    101. Long var10000 = this.getId();
    102. return "User(id=" + var10000 + ", name=" + this.getName() + ", age=" + this.getAge() + ", email=" + this.getEmail() + ")";
    103. }

    }

  • 使用后

    package com.cunyu.user.entity;

    import lombok.Data;

    /**

    • Created with IntelliJ IDEA.
      *
    • @author : zhangliang
    • @version : 1.0
    • @project : User
    • @package : com.cunyu.user.entity
    • @className : User
    • @createTime : 2021/8/6 17:14
    • @description : 用户实体类
      */

    @Data
    public class User {

    1. private Long id;
    2. private String name;
    3. private Integer age;
    4. private String email;

    }

@Setter

注解在 上:为该类所有属性均提供 set 方法,同时提供 默认构造方法

  • 使用前

    package com.cunyu.user.entity;

    public class User {

    1. private Long id;
    2. private String name;
    3. private Integer age;
    4. private String email;
    5. public User() {
    6. }
    7. public void setId(final Long id) {
    8. this.id = id;
    9. }
    10. public void setName(final String name) {
    11. this.name = name;
    12. }
    13. public void setAge(final Integer age) {
    14. this.age = age;
    15. }
    16. public void setEmail(final String email) {
    17. this.email = email;
    18. }

    }

  • 使用后

    package com.cunyu.user.entity;

    import lombok.Setter;

    /**

    • Created with IntelliJ IDEA.
      *
    • @author : zhangliang
    • @version : 1.0
    • @project : User
    • @package : com.cunyu.user.entity
    • @className : User
    • @createTime : 2021/8/6 17:14
    • @description : 用户实体类
      */

    @Setter
    public class User {

    1. private Long id;
    2. private String name;
    3. private Integer age;
    4. private String email;

    }

注解在 属性 上:为该属性提供 set 方法,同时提供 默认构造方法

  • 使用前

    package com.cunyu.user.entity;

    public class User {

    1. private Long id;
    2. private String name;
    3. private Integer age;
    4. private String email;
    5. public User() {
    6. }
    7. public void setId(final Long id) {
    8. this.id = id;
    9. }

    }

  • 使用后

    package com.cunyu.user.entity;

    import lombok.Setter;

    /**

    • Created with IntelliJ IDEA.
      *
    • @author : zhangliang
    • @version : 1.0
    • @project : User
    • @package : com.cunyu.user.entity
    • @className : User
    • @createTime : 2021/8/6 17:14
    • @description : 用户实体类
      */

    public class User {

    1. @Setter
    2. private Long id;
    3. private String name;
    4. private Integer age;
    5. private String email;

    }

@Getter

注解在 上:为该类所有属性均提供 get 方法,同时提供 默认构造方法

  • 使用前

    package com.cunyu.user.entity;

    public class User {

    1. private Long id;
    2. private String name;
    3. private Integer age;
    4. private String email;
    5. public User() {
    6. }
    7. public Long getId() {
    8. return this.id;
    9. }
    10. public String getName() {
    11. return this.name;
    12. }
    13. public Integer getAge() {
    14. return this.age;
    15. }
    16. public String getEmail() {
    17. return this.email;
    18. }

    }

  • 使用后

    package com.cunyu.user.entity;

    import lombok.Getter;

    /**

    • Created with IntelliJ IDEA.
      *
    • @author : zhangliang
    • @version : 1.0
    • @project : User
    • @package : com.cunyu.user.entity
    • @className : User
    • @createTime : 2021/8/6 17:14
    • @description : 用户实体类
      */

    @Getter
    public class User {

    1. private Long id;
    2. private String name;
    3. private Integer age;
    4. private String email;

    }

注解在 属性 上:为该属性提供 get 方法,同时提供 默认构造方法

  • 使用前

    package com.cunyu.user.entity;

    public class User {

    1. private Long id;
    2. private String name;
    3. private Integer age;
    4. private String email;
    5. public User() {
    6. }
    7. public Long getId() {
    8. return this.id;
    9. }

    }

  • 使用后

    package com.cunyu.user.entity;

    import lombok.Getter;

    /**

    • Created with IntelliJ IDEA.
      *
    • @author : zhangliang
    • @version : 1.0
    • @project : User
    • @package : com.cunyu.user.entity
    • @className : User
    • @createTime : 2021/8/6 17:14
    • @description : 用户实体类
      */

    public class User {

    1. @Getter
    2. private Long id;
    3. private String name;
    4. private Integer age;
    5. private String email;

    }

@ToString

注解在 上:生成所有参数的 toString() 方法,同时提供 默认构造方法

  • 使用前

    package com.cunyu.user.entity;

    public class User {

    1. private Long id;
    2. private String name;
    3. private Integer age;
    4. private String email;
    5. public User() {
    6. }
    7. public String toString() {
    8. return "User(id=" + this.id + ", name=" + this.name + ", age=" + this.age + ", email=" + this.email + ")";
    9. }

    }

  • 使用后

    package com.cunyu.user.entity;

    import lombok.ToString;

    /**

    • Created with IntelliJ IDEA.
      *
    • @author : zhangliang
    • @version : 1.0
    • @project : User
    • @package : com.cunyu.user.entity
    • @className : User
    • @createTime : 2021/8/6 17:14
    • @description : 用户实体类
      */

    @ToString
    public class User {

    1. private Long id;
    2. private String name;
    3. private Integer age;
    4. private String email;

    }

@Value

注解在 上:生成 get 方法,以及 equals、hashCode、toString 方法,同时提供 含所有参数的构造方法

  • 使用前

    package com.cunyu.user.entity;

    public final class User {

    1. private final Long id;
    2. private final String name;
    3. private final Integer age;
    4. private final String email;
    5. public User(final Long id, final String name, final Integer age, final String email) {
    6. this.id = id;
    7. this.name = name;
    8. this.age = age;
    9. this.email = email;
    10. }
    11. public Long getId() {
    12. return this.id;
    13. }
    14. public String getName() {
    15. return this.name;
    16. }
    17. public Integer getAge() {
    18. return this.age;
    19. }
    20. public String getEmail() {
    21. return this.email;
    22. }
    23. public boolean equals(final Object o) {
    24. if (o == this) {
    25. return true;
    26. } else if (!(o instanceof User)) {
    27. return false;
    28. } else {
    29. User other;
    30. label56: {
    31. other = (User)o;
    32. Object this$id = this.getId();
    33. Object other$id = other.getId();
    34. if (this$id == null) {
    35. if (other$id == null) {
    36. break label56;
    37. }
    38. } else if (this$id.equals(other$id)) {
    39. break label56;
    40. }
    41. return false;
    42. }
    43. label49: {
    44. Object this$age = this.getAge();
    45. Object other$age = other.getAge();
    46. if (this$age == null) {
    47. if (other$age == null) {
    48. break label49;
    49. }
    50. } else if (this$age.equals(other$age)) {
    51. break label49;
    52. }
    53. return false;
    54. }
    55. Object this$name = this.getName();
    56. Object other$name = other.getName();
    57. if (this$name == null) {
    58. if (other$name != null) {
    59. return false;
    60. }
    61. } else if (!this$name.equals(other$name)) {
    62. return false;
    63. }
    64. Object this$email = this.getEmail();
    65. Object other$email = other.getEmail();
    66. if (this$email == null) {
    67. if (other$email != null) {
    68. return false;
    69. }
    70. } else if (!this$email.equals(other$email)) {
    71. return false;
    72. }
    73. return true;
    74. }
    75. }
    76. public int hashCode() {
    77. int PRIME = true;
    78. int result = 1;
    79. Object $id = this.getId();
    80. int result = result * 59 + ($id == null ? 43 : $id.hashCode());
    81. Object $age = this.getAge();
    82. result = result * 59 + ($age == null ? 43 : $age.hashCode());
    83. Object $name = this.getName();
    84. result = result * 59 + ($name == null ? 43 : $name.hashCode());
    85. Object $email = this.getEmail();
    86. result = result * 59 + ($email == null ? 43 : $email.hashCode());
    87. return result;
    88. }
    89. public String toString() {
    90. Long var10000 = this.getId();
    91. return "User(id=" + var10000 + ", name=" + this.getName() + ", age=" + this.getAge() + ", email=" + this.getEmail() + ")";
    92. }

    }

  • 使用后

    package com.cunyu.user.entity;

    import lombok.Value;

    /**

    • Created with IntelliJ IDEA.
      *
    • @author : zhangliang
    • @version : 1.0
    • @project : User
    • @package : com.cunyu.user.entity
    • @className : User
    • @createTime : 2021/8/6 17:14
    • @description : 用户实体类
      */

    @Value
    public class User {

    1. private Long id;
    2. private String name;
    3. private Integer age;
    4. private String email;

    }

@AllArgsConstructor

注解在 上:为类提供一个 全参构造方法,但此时不再提供默认构造方法;

  • 使用前

    package com.cunyu.user.entity;

    public class User {

    1. private Long id;
    2. private String name;
    3. private Integer age;
    4. private String email;
    5. public User(final Long id, final String name, final Integer age, final String email) {
    6. this.id = id;
    7. this.name = name;
    8. this.age = age;
    9. this.email = email;
    10. }

    }

  • 使用后

    package com.cunyu.user.entity;

    import lombok.AllArgsConstructor;

    /**

    • Created with IntelliJ IDEA.
      *
    • @author : zhangliang
    • @version : 1.0
    • @project : User
    • @package : com.cunyu.user.entity
    • @className : User
    • @createTime : 2021/8/6 17:14
    • @description : 用户实体类
      */

    @AllArgsConstructor
    public class User {

    1. private Long id;
    2. private String name;
    3. private Integer age;
    4. private String email;

    }

@NoArgsConstructor

注解在 上:为类提供一个 无参构造方法

  • 使用前

    package com.cunyu.user.entity;

    public class User {

    1. private Long id;
    2. private String name;
    3. private Integer age;
    4. private String email;
    5. public User() {
    6. }

    }

  • 使用后

    package com.cunyu.user.entity;

    import lombok.NoArgsConstructor;

    /**

    • Created with IntelliJ IDEA.
      *
    • @author : zhangliang
    • @version : 1.0
    • @project : User
    • @package : com.cunyu.user.entity
    • @className : User
    • @createTime : 2021/8/6 17:14
    • @description : 用户实体类
      */

    @NoArgsConstructor
    public class User {

    1. private Long id;
    2. private String name;
    3. private Integer age;
    4. private String email;

    }

@RequiredArgsConstructor

注解在 上:使用类中所有带 @NonNull 注解的或带有 final 修饰的成员变量生成对应构造方法;

  • 使用前

    package com.cunyu.user.entity;

    import lombok.NonNull;

    public class User {

    1. @NonNull
    2. private Long id;
    3. private String name;
    4. private Integer age;
    5. @NonNull
    6. private String email;
    7. public User(@NonNull final Long id, @NonNull final String email) {
    8. if (id == null) {
    9. throw new NullPointerException("id is marked non-null but is null");
    10. } else if (email == null) {
    11. throw new NullPointerException("email is marked non-null but is null");
    12. } else {
    13. this.id = id;
    14. this.email = email;
    15. }
    16. }

    }

  • 使用后

    package com.cunyu.user.entity;

    import lombok.RequiredArgsConstructor;

    /**

    • Created with IntelliJ IDEA.
      *
    • @author : zhangliang
    • @version : 1.0
    • @project : User
    • @package : com.cunyu.user.entity
    • @className : User
    • @createTime : 2021/8/6 17:14
    • @description : 用户实体类
      */

    @RequiredArgsConstructor
    public class User {

    1. @NonNull
    2. private Long id;
    3. private String name;
    4. private Integer age;
    5. @NonNull
    6. private String email;

    }

@NonNull

注解在 属性 上,自动生成一个关于该参数的非空检查,若参数为 null,则抛出一个空指针异常,同时提供 默认构造方法,具体用法可以参照上面的例子;

@EqualsAndHashCode

注解在 上,生成 equals、canEquals、hasnCode 方法,同时会生成默认构造方法;

  • 使用前

    //
    // Source code recreated from a .class file by IntelliJ IDEA
    // (powered by FernFlower decompiler)
    //

    package com.cunyu.user.entity;

    public class User {

    1. private Long id;
    2. private String name;
    3. private Integer age;
    4. private String email;
    5. public User() {
    6. }
    7. public boolean equals(final Object o) {
    8. if (o == this) {
    9. return true;
    10. } else if (!(o instanceof User)) {
    11. return false;
    12. } else {
    13. User other = (User)o;
    14. if (!other.canEqual(this)) {
    15. return false;
    16. } else {
    17. label59: {
    18. Object this$id = this.id;
    19. Object other$id = other.id;
    20. if (this$id == null) {
    21. if (other$id == null) {
    22. break label59;
    23. }
    24. } else if (this$id.equals(other$id)) {
    25. break label59;
    26. }
    27. return false;
    28. }
    29. Object this$age = this.age;
    30. Object other$age = other.age;
    31. if (this$age == null) {
    32. if (other$age != null) {
    33. return false;
    34. }
    35. } else if (!this$age.equals(other$age)) {
    36. return false;
    37. }
    38. Object this$name = this.name;
    39. Object other$name = other.name;
    40. if (this$name == null) {
    41. if (other$name != null) {
    42. return false;
    43. }
    44. } else if (!this$name.equals(other$name)) {
    45. return false;
    46. }
    47. Object this$email = this.email;
    48. Object other$email = other.email;
    49. if (this$email == null) {
    50. if (other$email != null) {
    51. return false;
    52. }
    53. } else if (!this$email.equals(other$email)) {
    54. return false;
    55. }
    56. return true;
    57. }
    58. }
    59. }
    60. protected boolean canEqual(final Object other) {
    61. return other instanceof User;
    62. }
    63. public int hashCode() {
    64. int PRIME = true;
    65. int result = 1;
    66. Object $id = this.id;
    67. int result = result * 59 + ($id == null ? 43 : $id.hashCode());
    68. Object $age = this.age;
    69. result = result * 59 + ($age == null ? 43 : $age.hashCode());
    70. Object $name = this.name;
    71. result = result * 59 + ($name == null ? 43 : $name.hashCode());
    72. Object $email = this.email;
    73. result = result * 59 + ($email == null ? 43 : $email.hashCode());
    74. return result;
    75. }

    }

  • 使用后

    package com.cunyu.user.entity;

    import lombok.EqualsAndHashCode;

    /**

    • Created with IntelliJ IDEA.
      *
    • @author : zhangliang
    • @version : 1.0
    • @project : User
    • @package : com.cunyu.user.entity
    • @className : User
    • @createTime : 2021/8/6 17:14
    • @description : 用户实体类
      */

    @EqualsAndHashCode
    public class User {

    1. private Long id;
    2. private String name;
    3. private Integer age;
    4. private String email;

    }

@Cleanup

注解在 局部变量 前,保证该变量代表的资源使用后自动关闭,默认调用资源的 close() 方法,若该资源有其它关闭方法,可用 @Cleanup("方法名") 来指定要调用的方法,同时提供 默认构造方法;

  • 使用前

    import java.io.*;

    public class CleanupExample {

    1. public static void main(String[] args) throws IOException {
    2. InputStream in = new FileInputStream(args[0]);
    3. try {
    4. OutputStream out = new FileOutputStream(args[1]);
    5. try {
    6. byte[] b = new byte[10000];
    7. while (true) {
    8. int r = in.read(b);
    9. if (r == -1) break;
    10. out.write(b, 0, r);
    11. }
    12. } finally {
    13. if (out != null) {
    14. out.close();
    15. }
    16. }
    17. } finally {
    18. if (in != null) {
    19. in.close();
    20. }
    21. }
    22. }

    }

  • 使用后

    import lombok.Cleanup;
    import java.io.*;

    public class CleanupExample {

    1. public static void main(String[] args) throws IOException {
    2. @Cleanup InputStream in = new FileInputStream(args[0]);
    3. @Cleanup OutputStream out = new FileOutputStream(args[1]);
    4. byte[] b = new byte[10000];
    5. while (true) {
    6. int r = in.read(b);
    7. if (r == -1) break;
    8. out.write(b, 0, r);
    9. }
    10. }

    }

@Synchronized

注解在 类方法 或 实例方法:效果与 synchronized 关键字相同,区别在于锁对象不同,对于类方法和实例方法,synchronized 关键字的锁对象分别是 类的 class 对象和 this 对象,而 @Synchronized 的锁对象分别是 私有静态 final 对象 lock 和 私有 final 对象 lock,也可以自己指定锁对象,同时提供默认构造方法;

  • 使用前

    public class SynchronizedExample {

    1. private static final Object $LOCK = new Object[0];
    2. private final Object $lock = new Object[0];
    3. private final Object readLock = new Object();
    4. public static void hello() {
    5. synchronized($LOCK) {
    6. System.out.println("world");
    7. }
    8. }
    9. public int answerToLife() {
    10. synchronized($lock) {
    11. return 42;
    12. }
    13. }
    14. public void foo() {
    15. synchronized(readLock) {
    16. System.out.println("bar");
    17. }
    18. }

    }

  • 使用后

    import lombok.Synchronized;

    public class SynchronizedExample {

    1. private final Object readLock = new Object();
    2. @Synchronized
    3. public static void hello() {
    4. System.out.println("world");
    5. }
    6. @Synchronized
    7. public int answerToLife() {
    8. return 42;
    9. }
    10. @Synchronized("readLock")
    11. public void foo() {
    12. System.out.println("bar");
    13. }

    }

@SneakyThrows

注解在 方法 上:将方法中的代码用 try-catch 语句包裹,捕获异常并在 catch 中用 Lombok.sneakyThrow(e) 将异常抛出,还可以用 @SneakyThrows(Exception.class) 的形式指定抛出异常类型,同时提供 默认构造方法

  • 使用前

    import lombok.Lombok;

    public class SneakyThrowsExample implements Runnable {

    1. public String utf8ToString(byte[] bytes) {
    2. try {
    3. return new String(bytes, "UTF-8");
    4. } catch (UnsupportedEncodingException e) {
    5. throw Lombok.sneakyThrow(e);
    6. }
    7. }
    8. public void run() {
    9. try {
    10. throw new Throwable();
    11. } catch (Throwable t) {
    12. throw Lombok.sneakyThrow(t);
    13. }
    14. }

    }

  • 使用后

    import lombok.SneakyThrows;

    public class SneakyThrowsExample implements Runnable {

    1. @SneakyThrows(UnsupportedEncodingException.class)
    2. public String utf8ToString(byte[] bytes) {
    3. return new String(bytes, "UTF-8");
    4. }
    5. @SneakyThrows
    6. public void run() {
    7. throw new Throwable();
    8. }

    }

@Log

注解在 上:主要用于我们记录日志信息,同时提供 默认构造方法。它封装了多个主流 Log 库,主要有如下几个;

  • @Log
  • @Slf4j
  • Log4j
  • Log4j2

总结

以上就是关于 Lombok 的相关使用小技巧了,如果你还没有使用过它,那就赶紧去试试吧!

最后,创作不易,如果你觉得我的文章对你有所帮助,那就来个一键三连吧!

参考资料

  1. https://projectlombok.org/features/all

发表评论

表情:
评论列表 (有 0 条评论,106人围观)

还没有评论,来说两句吧...

相关阅读

    相关 总结之Lombok安装使用介绍

    Lombok是一个通过注解的形式或简单关键字简化和消除Java应用程序中一些必须但是重复或显得臃肿的样板代码的实用工具。 以前使用lombok只是基础应用,没有系统的总结