首页 > 技术文章 > 了解Lombok插件

wulachen 2019-04-11 18:37 原文

Lombok是什么

Lombok可以通过注解形式帮助开发人员解决POJO冗长问题,帮助构造简洁和规范的代码,通过注解可产生相应的方法。

Lombok如何在IDEA中使用

我们都知道,使用一种工具,一定要在Maven中添加相应的依赖

在pom.xml中添加依赖

 

<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.6</version>
 </dependency>

 

然而,你会发现除了依赖,你还需要下载IntelliJ Lombok plugin插件

在IDEA中下载插件

  • 打开File-->Settings(Ctrl+Alt+S)
  • Plugins查找Lombok
  • 安装

Lombok常用注解

  • @Getter和@Setter

         Lombok为POJO自动生成getter和setter方法

  • @ToString

         自动生成toString()方法,默认情况,按顺序(以“,”分隔)打印你的类名称以及每个字段。也可以设置不包含哪些字段@ToString(exclude = {“id”,”name”})

  • @EqualsAndHashCode

         自动重写Equals和hashCode方法

  • @AllArgsConstructor

         会生成一个含所有参数的构造函数

  • @NoArgsConstructor

         会生成一个无参构造函数

  • @Data

         包含@Getter、@Setter、@ToString、@EqualsAndHashCode和@NoArgsConstructor几项功能

  • @Slf4j

         类上注解,直接调用log即可。log.info(****)

  • @Cleanup

        自动化关闭流,相当于jdk1.7中的try with resource

     

@Cleanup
InputStream in = new FileInputStream("***");
@Cleanup
OutputStream out = new FileOutputStream("***");
  • @NonNull

public NonNullExample(Student student){
      this.student = student;
}

转换成:

public NonNullExample(Student student){
    if(student == null){
          throw new NullPointException("student");
    }
    this.student = student;
}
  • @Synchronized

       给方法加上同步锁,建议在代码块中写Synchronized

参考文章  链接:https://www.cnblogs.com/qnight/p/8997493.html 

推荐阅读