Java Lombok不常用注解

Posted fengyehongWorld

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java Lombok不常用注解相关的知识,希望对你有一定的参考价值。

参考资料

  1. 最全的 lombok 注解详情(随着版本不定时更新)
  2. @Accessors 注解极简教程
  3. Lombok工具 : 常用注解介绍 (全)

目录


一. @Accessors

  • 可以同时作用于类和属性上,属性上的优先级 > 类上的优先级

1.1 fluent 属性

  • 默认值为false
  • 当为 true 时,对应字段的 getter 方法前面就没有 get,setter 方法就不会有 set
import lombok.Data;
import lombok.experimental.Accessors;

@Data
@Accessors(fluent = true)
public class Student 

    private String personId;

    private String personName;

    private String age;

    private String address;

    public static void main(String[] args) 
        
        Student student = new Student();
        
        // 不需要set
        student.age("1");
        student.address("地球");
    
        // 不需要get
        student.personId();
        student.personName();
    

1.2 chain 属性

  • 默认值为false
  • 当为 true 时,对应字段的 setter 方法调用后,会返回当前对象
import lombok.Data;
import lombok.experimental.Accessors;

@Data
// 左右于类上,表示所有的属性都可以链式调用
@Accessors(chain = true)
public class Student 

    private String personId;

    private String personName;
	
	// 作用于属性上,表示这个属性不链式调用
    @Accessors(chain = false)
    private String age;

    private String address;

    public static void main(String[] args) 

        Student student = new Student();

        student.setPersonId("1")
                .setPersonName("贾飞天")
                // age属性并不链式调用,所以不会返回对象本身
                .setAge("10");
    

1.3 prefix 属性

  • 该属性是一个字符串数组
  • 当该数组有值时,表示忽略字段中对应的前缀,生成对应的 getter 和 setter 方法。
import lombok.Data;
import lombok.experimental.Accessors;

@Data
// 忽略属性前缀person和human,并且链式调用
@Accessors(prefix = "person", "human", chain = true)
public class Student 

    private String personId;

    private String humanName;
    
    private String age;

    private String address;

    public static void main(String[] args) 

        Student student = new Student();
        // 前缀person和human被忽略
        student.setId("1")
                .setName("贾飞天")
                .setAge("18")
                .setAddress("地球");
    

二. @Builder

  • 通过建造者模式创建对象
  • 会生成一个全参的构造函数,如果我们使用无参构造函数的话就会报错
import lombok.Builder;
import lombok.ToString;

@Builder
@ToString
public class Student 

    private String personId;

    private String humanName;

    private String age;
	
	// 非 final 的字段可以有默认值
    @Builder.Default
    private String address = "地球";

    public static void main(String[] args) 

        Student student = Student.builder()
                .personId("1")
                .humanName("贾飞天")
                .age("10")
                // 没有创建address属性
                .build();
        System.out.println(student);
        /*
        	因为我们使用@Builder.Default给address指定了默认值
        	Student(personId=1, humanName=贾飞天, age=10, address=地球)
		*/
    

三. @Singular

  • 该注解需要配合@Builder注解使用,用于注解一个集合字段
  • 如果没有指定value值的话,那么集合字段名需要是复数形式
  • 如果指定了value值,集合字段名就是我们指定的value值
  • 会生成添加元素方法向集合添加单个元素
import lombok.Builder;
import lombok.Data;
import lombok.Singular;

import java.util.List;

@Builder
@Data
public class Student 

    private String personId;

    private String humanName;

    private String age;

    /**
     * 属性名结尾不为 s ,
     * 因此必须在@Singular注解中手动指定构建时使用的名称
     */
    @Singular("address")
    private List<String> addressList;

    /**
     * 属性名结尾为 s,
     * 因此可以不手动指定构建时使用的名称,该名称为去掉s之后的属性名
     */
    @Singular
    private List<String> hobbys;

    public static void main(String[] args) 


        Student student = Student.builder()
                .personId("110")
                .humanName("贾飞天")
                // 可以一个一个向集合中添加元素,无需创建一个集合
                .address("地球").address("火星")
                .hobby("吃饭").hobby("睡觉")
                .build();
        System.out.println(student);
        /**
         * Student(
         *  personId=110,
         *  humanName=贾飞天,
         *  age=null,
         *  addressList=[地球, 火星],
         *  hobbys=[吃饭, 睡觉]
         * )
         */
    

四. @Cleanup

  • 作用于局部变量,可以自动关闭资源
  • 仅针对实现了java.io.Closeable接口的对象有效
import lombok.Cleanup;
import java.io.File;
import java.io.FileInputStream;

public static void main(String[] args) throws IOException 

    @Cleanup FileInputStream inputStream = new FileInputStream(new File("D:\\\\test\\\\application.yml"));
    byte[] bytes = inputStream.readAllBytes();
    System.out.println(Arrays.toString(bytes));

👉编译后

五. @RequiredArgsConstructor

⏹具体使用请参考这篇博客
SpringBoot 使用lombok的@RequiredArgsConstructor注解进行Bean注入

lombok常见注解

一、使用lombok简化代码

lombok提供了很多注解,在编译时候生成java代码,代替了手工编写一些简单的代码,使程序员可以关注更重要的实现。

二、常用注解

以model为例

public class DataDemo {
    private Integer id;
    private String name;
    private Date time;
}

一下是添加不同lombok注解的编译结果示例,编译结果很简单,不需要做什么说明,直接上代码:

@Getter / @Setter

技术分享图片
public class GetterSetterDemo {
    private Integer id;
    private String name;
    private Date time;

    public GetterSetterDemo() {  }

    public Integer getId() { return this.id; }

    public String getName() { return this.name; }

    public Date getTime() { return this.time; }

    public void setId(Integer id) { this.id = id; }

    public void setName(String name) { this.name = name; }

    public void setTime(Date time) { this.time = time; }
}
View Code

@ToString

model上添加注解:@ToString(exclude = {"id"}, includeFieldNames = false)

技术分享图片
public class ToStringDemo {
    private Integer id;
    private String name;
    private Date time;

    public ToStringDemo() {  }

    public String toString() {
        return "ToStringDemo(" + this.name + ", " + this.time + ")";
    }
}
View Code

@Data

@Data 注解相当于 Getter + Setter + ToString + @RequiredArgsConstrutor,可以用在pojo上

技术分享图片
public class DataDemo {
    private Integer id;
    private String name;
    private Date time;

    public DataDemo() {  }

    public Integer getId() { return this.id;}

    public String getName() { return this.name; }

    public Date getTime() { return this.time; }

    public void setId(Integer id) { this.id = id; }

    public void setName(String name) { this.name = name; }

    public void setTime(Date time) { this.time = time; }

    public boolean equals(Object o) { ... }

    protected boolean canEqual(Object other) { ... }

    public int hashCode() { ... }

    public String toString() {
        return "DataDemo(id=" + this.getId() + ", name=" + this.getName() + ", time=" + this.getTime() + ")";
    }
}
View Code

@Builder

技术分享图片
public class BuilderDemo {
    private Integer id;
    private String name;
    private Date time;

    @ConstructorProperties({"id", "name", "time"})
    BuilderDemo(Integer id, String name, Date time) {
        this.id = id;
        this.name = name;
        this.time = time;
    }

    public static BuilderDemo.BuilderDemoBuilder builder() {
        return new BuilderDemo.BuilderDemoBuilder();
    }

    public static class BuilderDemoBuilder {
        private Integer id;
        private String name;
        private Date time;

        BuilderDemoBuilder() {
        }

        public BuilderDemo.BuilderDemoBuilder id(Integer id) {
            this.id = id;
            return this;
        }

        public BuilderDemo.BuilderDemoBuilder name(String name) {
            this.name = name;
            return this;
        }

        public BuilderDemo.BuilderDemoBuilder time(Date time) {
            this.time = time;
            return this;
        }

        public BuilderDemo build() {
            return new BuilderDemo(this.id, this.name, this.time);
        }

        public String toString() {
            return "BuilderDemo.BuilderDemoBuilder(id=" + this.id + ", name=" + this.name + ", time=" + this.time + ")";
        }
    }
}
View Code

构造函数

@AllArgsConstructor    全部参数构造函数

@NoArgsConstructor   无参数构造函数

@RequiredArgsConstructor   NoNull参数和常量构造函数

技术分享图片
/**@AllArgsConstructor*/
public class AllArgsConstructorDemo {
    private Integer id;
    private String name;
    private Date time;

    @ConstructorProperties({"id", "name", "time"})
    public AllArgsConstructorDemo(Integer id, String name, Date time) {
        this.id = id;
        this.name = name;
        this.time = time;
    }
}


/**@NoArgsConstructor*/
public class NoArgsConstructorDemo {
    private Integer id;
    private String name;
    private Date time;

    public NoArgsConstructorDemo() {  }
}


/**@RequiredArgsConstructor(staticName = "of")*/
public class RequiredArgsConstructorDemo {
    private Integer id;
    private String name;
    private Date time;

    private RequiredArgsConstructorDemo() {  }

    public static RequiredArgsConstructorDemo of() {
        return new RequiredArgsConstructorDemo();
    }
}

/**@RequiredArgsConstructor(staticName = "of")*/
public class RequiredArgsConstructorDemo {
    private Integer id;
    @NonNull
    private String name;
    @NonNull
    private Date time;

    @ConstructorProperties({"name", "time"})
    private RequiredArgsConstructorDemo(@NonNull String name, @NonNull Date time) {
        if(name == null) {
            throw new NullPointerException("name");
        } else if(time == null) {
            throw new NullPointerException("time");
        } else {
            this.name = name;
            this.time = time;
        }
    }

    public static RequiredArgsConstructorDemo of(@NonNull String name, @NonNull Date time) {
        return new RequiredArgsConstructorDemo(name, time);
    }
}
View Code

@Value

技术分享图片
public final class ValueDemo {
    private final Integer id;
    private final String name;
    private final Date time;

    @ConstructorProperties({"id", "name", "time"})
    public ValueDemo(Integer id, String name, Date time) {
        this.id = id;
        this.name = name;
        this.time = time;
    }

    public Integer getId() {
        return this.id;
    }

    public String getName() {
        return this.name;
    }

    public Date getTime() {
        return this.time;
    }

    public boolean equals(Object o) { ... }

    public int hashCode() { ... }

    public String toString() {
        return "ValueDemo(id=" + this.getId() + ", name=" + this.getName() + ", time=" + this.getTime() + ")";
    }
}
View Code

 

以上是关于Java Lombok不常用注解的主要内容,如果未能解决你的问题,请参考以下文章

阿昌教你使用常用Lombok@注解

阿昌教你使用常用Lombok@注解

lombok常见注解

[Java 开发利器Lombok] 常用注解演示

lombok介绍

解决IDEA与lombok插件不兼容导致的@注解不可用的问题