当前位置:   article > 正文

springboot依赖lombok插件、lombok常用注解

lombok插件

 ——springboot依赖lombok插件、lombok常用注解

1 lombok插件

1.1 lombok插件简介

        官方介绍如下:

        意思是:lombok是一个能自动插入到编辑器和构建工具的java库。目的是为了简化java代码,开发者不需要写setter、getter和构造方法等,只需要几个或多个lombok注解就能实现。

         Lombok能以简单的注解形式来简化java代码,提高开发人员的开发效率。例如开发中经常需要写的pojo,都需要花时间去添加相应的getter、setter、构造器和equals等方法,当属性多时会出现大量的getter/setter方法,维护起来很麻烦,也容易出错。

1.2 springboot依赖lombok插件

        springboot中只需要依赖lombok的jar包就可使用Lombok。

        (1)方法一:可以在官网(Download)下载jar包:

        (2)方法二: 可以使用maven添加依赖:

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

2 lombok常用注解

2.1 @NotNull

        @NotNull注解如果设置在一个属性上,lombok将在自动生成的方法/构造函数体的开头插入一个空检查,抛出NullPointerException,并将参数的名称作为message。

lombok注解实现:

  1. import lombok.AccessLevel;
  2. import lombok.RequiredArgsConstructor;
  3. import lombok.AllArgsConstructor;
  4. import lombok.NonNull;
  5. @RequiredArgsConstructor(staticName = "of")
  6. @AllArgsConstructor(access = AccessLevel.PROTECTED)
  7. public class ConstructorExample<T> {
  8.   private int x, y;
  9.   @NonNull private T description;
  10.   
  11.   @NoArgsConstructor
  12.   public static class NoArgsExample {
  13.     @NonNull private String field;
  14.   }
  15. }

等价代码:

  1. public class ConstructorExample<T> {
  2.   private int x, y;
  3.   @NonNull private T description;
  4.   
  5.   private ConstructorExample(T description) {
  6. //空检查
  7.     if (description == nullthrow new NullPointerException("description");
  8.     this.description = description;
  9.   }
  10.   
  11.   public static <T> ConstructorExample<T> of(T description) {
  12.     return new ConstructorExample<T>(description);
  13.   }
  14.   
  15.   @java.beans.ConstructorProperties({"x""y""description"})
  16.   protected ConstructorExample(int x, int y, T description) {
  17. //空检查
  18.     if (description == nullthrow new NullPointerException("description");
  19.     this.x = x;
  20.     this.y = y;
  21.     this.description = description;
  22.   }
  23.   
  24.   public static class NoArgsExample {
  25.     @NonNull private String field;
  26.     
  27.     public NoArgsExample() {
  28.     }
  29.   }
  30. }

2.2 @NoArgsConstructor、@RequiredArgsConstructor和@AllArgsConstructor

2.2.1 @NoArgsConstructor

        生成不带参数的构造方法,即:无参构造方法。@NoArgsConstructor等价于:

  1. public MessageInfo() {
  2. }

        如果存在被final修饰的属性,那么会编译失败。

         可以设置force属性值为true,来避免编译错误。但是所有final修饰的属性会被初始化为final字段初始化为:0 或null 或 false。也就是说包装类型会被初始化为null,简单类型初始化为0或false。

2.2.2 @RequiredArgsConstructor

        只为final / @non-null修饰字段(不包括static修饰的)生成带参数的构造方法。

2.2.3 @AllArgsConstructor

描述:为所有字段(包括final修饰的,不包括static修饰的)生成带参数的构造方法,即:全参数构造方法。

2.3 @Getter和@Setter

         lombok官方文档的描述:

 lombok注解实现:

  1. import lombok.AccessLevel;
  2. import lombok.Getter;
  3. import lombok.Setter;
  4. public class GetterSetterExample {
  5.   /**
  6.    * Age of the person. Water is wet.
  7.    * 
  8.    * @param age New value for this person's age. Sky is blue.
  9.    * @return The current value of this person's age. Circles are round.
  10.    */
  11.   @Getter @Setter private int age = 10;
  12.   
  13.   /**
  14.    * Name of the person.
  15.    * -- SETTER --
  16.    * Changes the name of this person.
  17.    * 
  18.    * @param name The new value.
  19.    */
  20.   @Setter(AccessLevel.PROTECTED) private String name;
  21.   
  22.   @Override public String toString() {
  23.     return String.format("%s (age: %d)", name, age);
  24.   }
  25. }

等价代码:

  1. public class GetterSetterExample {
  2.   /**
  3.    * Age of the person. Water is wet.
  4.    */
  5.   private int age = 10;
  6.   /**
  7.    * Name of the person.
  8.    */
  9.   private String name;
  10.   
  11.   @Override public String toString() {
  12.     return String.format("%s (age: %d)", name, age);
  13.   }
  14.   
  15.   /**
  16.    * Age of the person. Water is wet.
  17.    *
  18.    * @return The current value of this person's age. Circles are round.
  19.    */
  20.   public int getAge() {
  21.     return age;
  22.   }
  23.   
  24.   /**
  25.    * Age of the person. Water is wet.
  26.    *
  27.    * @param age New value for this person's age. Sky is blue.
  28.    */
  29.   public void setAge(int age) {
  30.     this.age = age;
  31.   }
  32.   
  33.   /**
  34.    * Changes the name of this person.
  35.    *
  36.    * @param name The new value.
  37.    */
  38.   protected void setName(String name) {
  39.     this.name = name;
  40.   }
  41. }

2.3.1 @Getter

        @Getter为非静态属性(non-static属性)生成getter方法;如果@Getter放在类上,则会为该类中所有非静态属性(non-static属性)生成getter方法。

2.3.2 @Setter

        @Setter为非静态(non-static属性)和非final修饰的属性生成setter方法;如果@Setter放在类上,则会为该类中所有非静态(non-static属性)和非final修饰的属性生成setter方法。

2.4 @ToString、@ToString.Exclude、@ToString.Include

2.4.1 @ToString

        为所有对象生成toString方法,该方法会打印对象的所有属性值。默认情况下,它将打印类名,以及按顺序打印每个字段(static静态属性除外),字段直接用逗号分隔。示例如下:

MessageInfo(msgId=1, content=null, count=null, enabled=null, remark=备注)

参数:

  1. includeFieldNames:boolean类型,指定是否打印所有属性,默认为true。
  2. callSuper:boolean类型,指定是否需要打印父类的属性,默认为false。

2.4.2 @ToString.Exclude

        指定不打印的属性列表(static静态属性除外)。需要搭配@ToString使用。

2.4.3 @ToString.Include

        指定要打印的属性列表(可以放在static静态属性上)。需要搭配@ToString使用。

Lombok实现:

  1. import lombok.ToString;
  2. @ToString
  3. public class ToStringExample {
  4.   private static final int STATIC_VAR = 10;
  5.   private String name;
  6.   private Shape shape = new Square(510);
  7.   private String[] tags;
  8.   @ToString.Exclude private int id;
  9.   
  10.   public String getName() {
  11.     return this.name;
  12.   }
  13.   
  14.   @ToString(callSuper=true, includeFieldNames=true)
  15.   public static class Square extends Shape {
  16.     private final int width, height;
  17.     
  18.     public Square(int width, int height) {
  19.       this.width = width;
  20.       this.height = height;
  21.     }
  22.   }
  23. }

等价代码:

  1. import java.util.Arrays;
  2. public class ToStringExample {
  3.   private static final int STATIC_VAR = 10;
  4.   private String name;
  5.   private Shape shape = new Square(510);
  6.   private String[] tags;
  7.   private int id;
  8.   
  9.   public String getName() {
  10.     return this.name;
  11.   }
  12.   
  13.   public static class Square extends Shape {
  14.     private final int width, height;
  15.     
  16.     public Square(int width, int height) {
  17.       this.width = width;
  18.       this.height = height;
  19.     }
  20.     
  21.     @Override public String toString() {
  22.       return "Square(super=" + super.toString() + ", width=" + this.width + ", height=" + this.height + ")";
  23.     }
  24.   }
  25.   
  26.   @Override public String toString() {
  27.     return "ToStringExample(" + this.getName() + ", " + this.shape + ", " + Arrays.deepToString(this.tags) + ")";
  28.   }
  29. }

2.5 @SneakyThrows

(1)@SneakyThrows注解原理:

        在java的异常体系中Exception异常有两种类型:
        1)编译时异常:普通Exception类,如:UnsupportedEncodingException、IOException

等。
        2)运行时异常:RuntimeException类,如:NullPointerException 空指针异常、

IndexOutOfBoundsException 数组越界异常等。
        第一种会强制要求抛出它的方法声明throws,调用者必须显式地去处理(try..catch)这个异常。设计的目的是为了提醒开发者处理一些场景中必然可能存在的异常情况。比如网络异常造成IOException。所有的运行时异常不需要捕获,编译时异常是一定要捕获,否则编译会报错。

        但是编写代码时,大部分情况下的异常,我们都是一路往外抛了事。所以渐渐的java程序员处理Exception的常见手段就是外面包一层RuntimeException,接着往上丢。这种解决思想尤其在Spring中到处出现。@SneakyThrows就是利用了这一机制,将当前方法抛出的异常,包装成RuntimeException,骗过编译器,使得调用点可以不用显示处理异常信息。

        处理异常的一般方式如下:

  1. try{
  2. //do work
  3. }catch(Exception e){
  4. throw new RuntimeException(e);
  5. }

        通过try...catch来捕获异常,并把异常封装成运行时异常后继续往上层抛去。代码中try...catch越多,代码就越臃肿。Lombok的@SneakyThrows注解就是为了消除这样的模板代码。

lombok注解实现:

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

等价代码:

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

        显然将异常封装为运行时异常RuntimeException的关键藏在Lombok.sneakyThrow(t);中。可能大家都会以为这个方法就是new RuntimeException()之类的。然而事实并非如此。阅读代码可以看出整个方法其实最核心的逻辑是throw (T)t;,利用泛型将我们传入的Throwable强转为RuntimeException。

  1. public static RuntimeException sneakyThrow(Throwable t) {
  2.     if (t == null) throw new NullPointerException("t");
  3.         return Lombok.<RuntimeException>sneakyThrow0(t);
  4.     }
  5. }
  6. private static <T extends Throwable> T sneakyThrow0(Throwable t) throws T {
  7.     throw (T)t;
  8. }

        那么问题来了,为什么这个地方可以对原来的异常进行强转为RuntimeExcption?以下为直接强转的代码,显然运行之后报类型转换异常。

  1. private void sneakyThrowsTest() {
  2. try {
  3. throw new Exception();
  4. } catch (Throwable e) {
  5. // 直接将e强转为RuntimeException,运行到这里会报类型转换异常。
  6. throw (RuntimeException)e;
  7. }
  8. }

        实际上,这种做法是一种通过泛型欺骗了编译器,让编译器在编译期不报错,而最后在JVM虚拟机中执行的字节码的并没有区别编译时异常和运行时异常,只有是不是和抛不抛异常而已。

(2)@SneakyThrows和@SneakyThrows(UnsupportedEncodingException.class)的区别:

        1)@SneakyThrows默认情况下会自动捕获Throwable类及其子类异常(也就是所有异常),然后封装成RuntimeException后抛出;

    2)@SneakyThrows(UnsupportedEncodingException.class) 或 @SneakyThrows(value = {IOException.class, UnsupportedEncodingException.class}):表示指定捕获某几种异常(包括子类异常)然后封装成RuntimeException后抛出,其他异常不处理。

2.6 @Synchronized

        作用同synchronized关键字,为防止并发访问实例对象方法或类静态方法。该注解需放在方法上。

        @Synchronized是synchronized方法修饰符的一个更安全的变体。与synchronized一样,注释只能用于静态方法和非静态方法。它的操作类似于synchronized关键字,但是又略有不同。不同点:修饰静态方法时,@Synchronized的锁是对象锁($LOCK);Synchronize关键字的锁是类锁。修饰非静态方法时,@Synchronized的锁是对象锁($lock);Synchronize关键字的锁是对象锁(this)。关键字锁定了这个字段,但是注释锁定了一个名为$lock的字段,该字段是私有的。注意,@Synchronized的锁是一个私有的(private)

        当然,我们可以在代码中手动创建$LOCK或$lock锁对象,如果我们定义了锁对象,那么lombok就不会自动创建$LOCK或$lock锁对象。

        我们也可以通过@Synchronized("锁对象名")方式来指定锁对象的名称。但是千万要注意,如果我们指定锁对象的名称,那么我们必须要手动定义该锁对象,lombok不会为我们创建该锁对象!

Lombok注解实现:

  1. import lombok.Synchronized;
  2. public class SynchronizedExample {
  3. //自定义的锁对象
  4.   private final Object readLock = new Object();
  5.   
  6.   @Synchronized
  7.   public static void hello() {
  8.     System.out.println("world");
  9.   }
  10.   
  11.   @Synchronized
  12.   public int answerToLife() {
  13.     return 42;
  14.   }
  15.   
  16.   @Synchronized("readLock")
  17.   public void foo() {
  18.     System.out.println("bar");
  19.   }
  20. }

等价代码:

  1. public class SynchronizedExample {
  2. //lombok自动生成的锁对象$LOCK
  3.   private static final Object $LOCK = new Object[0];
  4. //lombok自动生成的锁对象$lock
  5.   private final Object $lock = new Object[0];
  6. //自定义的锁对象
  7.   private final Object readLock = new Object();
  8.   
  9.   public static void hello() {
  10.     synchronized($LOCK) {
  11.       System.out.println("world");
  12.     }
  13.   }
  14.   
  15.   public int answerToLife() {
  16.     synchronized($lock) {
  17.       return 42;
  18.     }
  19.   }
  20.   
  21.   public void foo() {
  22.     synchronized(readLock) {
  23.       System.out.println("bar");
  24.     }
  25.   }
  26. }

2.7 @EqualsAndHashCode

        根据对象的所有属性,生成equals和hashCode方法。

2.8 @Builder

        @Builder注解可以为你的类生成复杂的构建器apis,自动生成所需的代码,使类可以用下面类似的代码实例化,例如:

  1. Person.builder()
  2. .name("Adam Savage")
  3. .city("San Francisco")
  4. .job("Mythbusters")
  5. .job("Unchained Reaction")
  6. .build();

        如果@Builder放在类上了,那么就会自动生成一个私有全参构造函数,并将所有字段作为参数(就好像类上加@AllArgsConstructor(access = AccessLevel.PRIVATE))。一般情况下@Builder搭配@Getter使用。

        一个带有@Builder注解的方法会生成以下7个东西:

  • An inner static class named FooBuilder, with the same type arguments as the static method (called the builder).
  • In the builder: One private non-static non-final field for each parameter of the target.
  • In the builder: A package private no-args empty constructor.
  • In the builder: A 'setter'-like method for each parameter of the target: It has the same type as that parameter and the same name. It returns the builder itself, so that the setter calls can be chained, as in the above example.
  • In the builder: A build() method which calls the method, passing in each field. It returns the same type that the target returns.
  • In the builder: A sensible toString() implementation.
  • In the class containing the target: A builder() method, which creates a new instance of the builder.

lombok注解实现:

  1. @Builder
  2. class Example<T> {
  3. private T foo;
  4. private final String bar;
  5. }

等价代码:

  1. class Example<T> {
  2. private T foo;
  3. private final String bar;
  4. private Example(T foo, String bar) {
  5. this.foo = foo;
  6. this.bar = bar;
  7. }
  8. public static <T> ExampleBuilder<T> builder() {
  9. return new ExampleBuilder<T>();
  10. }
  11. public static class ExampleBuilder<T> {
  12. private T foo;
  13. private String bar;
  14. private ExampleBuilder() {}
  15. public ExampleBuilder foo(T foo) {
  16. this.foo = foo;
  17. return this;
  18. }
  19. public ExampleBuilder bar(String bar) {
  20. this.bar = bar;
  21. return this;
  22. }
  23. @java.lang.Override public String toString() {
  24. return "ExampleBuilder(foo = " + foo + ", bar = " + bar + ")";
  25. }
  26. public Example build() {
  27. return new Example(foo, bar);
  28. }
  29. }
  30. }

2.9 @Data和@Value

2.9.1 @Data

        @Data注解等价于:@Getter + @Setter + @RequiredArgsConstructor + @ToString  + @EqualsAndHashCode。

        @Data为所有字段生成getter、构造函数、toString、hashCode和equals方法,检查所有@NotNull约束字段。也会为所有非final字段生成setter方法。具体详见等价的注解。

2.9.2 @Value

      @Value注解等价于: @Getter+ @AllArgsConstructor + @ToString + @EqualsAndHashCode + @FieldDefaults(makeFinal=true, level=AccessLevel.PRIVATE) 

        @Value是@Data的不可变变量。默认情况下,所有属性字段都被设置为private和final,类本身也被设置为final,并且不会为属性生成setter方法。像@Data一样,还生成了有用的toString()、equals()和hashCode()方法,并为每个字段生成getter方法,还生成了覆盖每个参数的构造函数(除了在字段声明中初始化的final字段)。        

lombok注解实现:

  1. import lombok.AccessLevel;
  2. import lombok.experimental.NonFinal;
  3. import lombok.experimental.Value;
  4. import lombok.experimental.With;
  5. import lombok.ToString;
  6. @Value public class ValueExample {
  7.   String name;
  8.   @With(AccessLevel.PACKAGE) @NonFinal int age;
  9.   double score;
  10.   protected String[] tags;
  11.   
  12.   @ToString(includeFieldNames=true)
  13.   @Value(staticConstructor="of")
  14.   public static class Exercise<T> {
  15.     String name;
  16.     T value;
  17.   }
  18. }

等价代码:

  1. import java.util.Arrays;
  2. public final class ValueExample {
  3.   private final String name;
  4.   private int age;
  5.   private final double score;
  6.   protected final String[] tags;
  7.   
  8.   @java.beans.ConstructorProperties({"name""age""score""tags"})
  9.   public ValueExample(String name, int age, double score, String[] tags) {
  10.     this.name = name;
  11.     this.age = age;
  12.     this.score = score;
  13.     this.tags = tags;
  14.   }
  15.   
  16.   public String getName() {
  17.     return this.name;
  18.   }
  19.   
  20.   public int getAge() {
  21.     return this.age;
  22.   }
  23.   
  24.   public double getScore() {
  25.     return this.score;
  26.   }
  27.   
  28.   public String[] getTags() {
  29.     return this.tags;
  30.   }
  31.   
  32.   @java.lang.Override
  33.   public boolean equals(Object o) {
  34.     if (o == thisreturn true;
  35.     if (!(o instanceof ValueExample)) return false;
  36.     final ValueExample other = (ValueExample)o;
  37.     final Object this$name = this.getName();
  38.     final Object other$name = other.getName();
  39.     if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false;
  40.     if (this.getAge() != other.getAge()) return false;
  41.     if (Double.compare(this.getScore(), other.getScore()) != 0return false;
  42.     if (!Arrays.deepEquals(this.getTags(), other.getTags())) return false;
  43.     return true;
  44.   }
  45.   
  46.   @java.lang.Override
  47.   public int hashCode() {
  48.     final int PRIME = 59;
  49.     int result = 1;
  50.     final Object $name = this.getName();
  51.     result = result * PRIME + ($name == null ? 43 : $name.hashCode());
  52.     result = result * PRIME + this.getAge();
  53.     final long $score = Double.doubleToLongBits(this.getScore());
  54.     result = result * PRIME + (int)($score >>> 32 ^ $score);
  55.     result = result * PRIME + Arrays.deepHashCode(this.getTags());
  56.     return result;
  57.   }
  58.   
  59.   @java.lang.Override
  60.   public String toString() {
  61.     return "ValueExample(name=" + getName() + ", age=" + getAge() + ", score=" + getScore() + ", tags=" + Arrays.deepToString(getTags()) + ")";
  62.   }
  63.   
  64.   ValueExample withAge(int age) {
  65.     return this.age == age ? this : new ValueExample(name, age, score, tags);
  66.   }
  67.   
  68.   public static final class Exercise<T> {
  69.     private final String name;
  70.     private final T value;
  71.     
  72.     private Exercise(String name, T value) {
  73.       this.name = name;
  74.       this.value = value;
  75.     }
  76.     
  77.     public static <T> Exercise<T> of(String name, T value) {
  78.       return new Exercise<T>(name, value);
  79.     }
  80.     
  81.     public String getName() {
  82.       return this.name;
  83.     }
  84.     
  85.     public T getValue() {
  86.       return this.value;
  87.     }
  88.     
  89.     @java.lang.Override
  90.     public boolean equals(Object o) {
  91.       if (o == thisreturn true;
  92.       if (!(o instanceof ValueExample.Exercise)) return false;
  93.       final Exercise<?> other = (Exercise<?>)o;
  94.       final Object this$name = this.getName();
  95.       final Object other$name = other.getName();
  96.       if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false;
  97.       final Object this$value = this.getValue();
  98.       final Object other$value = other.getValue();
  99.       if (this$value == null ? other$value != null : !this$value.equals(other$value)) return false;
  100.       return true;
  101.     }
  102.     
  103.     @java.lang.Override
  104.     public int hashCode() {
  105.       final int PRIME = 59;
  106.       int result = 1;
  107.       final Object $name = this.getName();
  108.       result = result * PRIME + ($name == null ? 43 : $name.hashCode());
  109.       final Object $value = this.getValue();
  110.       result = result * PRIME + ($value == null ? 43 : $value.hashCode());
  111.       return result;
  112.     }
  113.     
  114.     @java.lang.Override
  115.     public String toString() {
  116.       return "ValueExample.Exercise(name=" + getName() + ", value=" + getValue() + ")";
  117.     }
  118.   }
  119. }

         至此,根据官方文档,详细通过示例介绍了lombok轻量级插件的使用。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/650755
推荐阅读
相关标签
  

闽ICP备14008679号