Lombok为啥这么牛逼?SpringBoot和IDEA官方都要支持它

2022-07-26,,,,

最近 idea 2020最后一个版本发布了 ,已经内置了lombok插件,springboot 2.1.x之后的版本也在starter中内置了lombok依赖。为什么他们都要支持lombok呢?今天我来讲讲lombok的使用,看看它有何神奇之处!

lombok简介

lombok是一款java代码功能增强库,在github上已有9.8k+star。它会自动集成到你的编辑器和构建工具中,从而使你的java代码更加生动有趣。通过lombok的注解,你可以不用再写getter、setter、equals等方法,lombok将在编译时为你自动生成。

lombok集成

首先我们需要在idea中安装好lombok插件,如果你使用的是最新版idea 2020.3,则lombok插件已经内置,无需安装。

之后在项目的pom.xml文件中添加lombok依赖,springboot 2.1.x版本后无需指定lombok版本,springboot在 spring-boot-dependencies 中已经内置。

<!--lombok依赖-->
<dependency>
 <groupid>org.projectlombok</groupid>
 <artifactid>lombok</artifactid>
 <optional>true</optional>
</dependency>

lombok使用

lombok中有很多注解,这些注解使得我们可以更加方便的编写java代码,下面介绍下这些注解的使用。

val

使用val注解可以取代任意类型作为局部变量,这样我们就不用写复杂的arraylist和map.entry类型了,具体例子如下。

/**
 * created by macro on 2020/12/16.
 */
public class valexample {

 public static void example() {
 //val代替arraylist<string>和string类型
 val example = new arraylist<string>();
 example.add("hello world!");
 val foo = example.get(0);
 system.out.println(foo.tolowercase());
 }

 public static void example2() {
 //val代替map.entry<integer,string>类型
 val map = new hashmap<integer, string>();
 map.put(0, "zero");
 map.put(5, "five");
 for (val entry : map.entryset()) {
  system.out.printf("%d: %s\n", entry.getkey(), entry.getvalue());
 }
 }

 public static void main(string[] args) {
 example();
 example2();
 }
}

当我们使用了val注解后,lombok会从局部变量的初始化表达式推断出具体类型,编译后会生成如下代码。

public class valexample {
 public valexample() {
 }

 public static void example() {
 arraylist<string> example = new arraylist();
 example.add("hello world!");
 string foo = (string)example.get(0);
 system.out.println(foo.tolowercase());
 }

 public static void example2() {
 hashmap<integer, string> map = new hashmap();
 map.put(0, "zero");
 map.put(5, "five");
 iterator var1 = map.entryset().iterator();

 while(var1.hasnext()) {
  entry<integer, string> entry = (entry)var1.next();
  system.out.printf("%d: %s\n", entry.getkey(), entry.getvalue());
 }

 }
}

@nonnull

在方法上使用@nonnull注解可以做非空判断,如果传入空值的话会直接抛出nullpointerexception。

/**
 * created by macro on 2020/12/16.
 */
public class nonnullexample {
 private string name;
 public nonnullexample(@nonnull string name){
 this.name = name;
 }

 public static void main(string[] args) {
 new nonnullexample("test");
 //会抛出nullpointerexception
 new nonnullexample(null);
 }
}

编译后会在构造器中添加非空判断,具体代码如下。

public class nonnullexample {
 private string name;

 public nonnullexample(@nonnull string name) {
 if (name == null) {
  throw new nullpointerexception("name is marked non-null but is null");
 } else {
  this.name = name;
 }
 }

 public static void main(string[] args) {
 new nonnullexample("test");
 new nonnullexample((string)null);
 }
}

@cleanup

当我们在java中使用资源时,不可避免地需要在使用后关闭资源。使用@cleanup注解可以自动关闭资源。

/**
 * created by macro on 2020/12/16.
 */
public class cleanupexample {
 public static void main(string[] args) throws ioexception {
 string instr = "hello world!";
 //使用输入输出流自动关闭,无需编写try catch和调用close()方法
 @cleanup bytearrayinputstream in = new bytearrayinputstream(instr.getbytes("utf-8"));
 @cleanup bytearrayoutputstream out = new bytearrayoutputstream();
 byte[] b = new byte[1024];
 while (true) {
  int r = in.read(b);
  if (r == -1) break;
  out.write(b, 0, r);
 }
 string outstr = out.tostring("utf-8");
 system.out.println(outstr);
 }
}

编译后lombok会生成如下代码。

public class cleanupexample {
 public cleanupexample() {
 }

 public static void main(string[] args) throws ioexception {
 string instr = "hello world!";
 bytearrayinputstream in = new bytearrayinputstream(instr.getbytes("utf-8"));

 try {
  bytearrayoutputstream out = new bytearrayoutputstream();

  try {
  byte[] b = new byte[1024];

  while(true) {
   int r = in.read(b);
   if (r == -1) {
   string outstr = out.tostring("utf-8");
   system.out.println(outstr);
   return;
   }

   out.write(b, 0, r);
  }
  } finally {
  if (collections.singletonlist(out).get(0) != null) {
   out.close();
  }

  }
 } finally {
  if (collections.singletonlist(in).get(0) != null) {
  in.close();
  }

 }
 }
}

@getter/@setter

有了@getter/@setter注解,我们再也不用编写getter/setter方法了。试想下之前即使我们使用idea自动生成getter/setter方法,如果类属性的类型和名称改了,又要重新生成getter/setter方法也是一件很麻烦的事情。

/**
 * created by macro on 2020/12/17.
 */
public class gettersetterexample {
 @getter
 @setter
 private string name;
 @getter
 @setter(accesslevel.protected)
 private integer age;

 public static void main(string[] args) {
 gettersetterexample example = new gettersetterexample();
 example.setname("test");
 example.setage(20);
 system.out.printf("name:%s age:%d",example.getname(),example.getage());
 }
}

编译后lombok会生成如下代码。

public class gettersetterexample {
 private string name;
 private integer age;

 public gettersetterexample() {
 }

 public string getname() {
 return this.name;
 }

 public void setname(final string name) {
 this.name = name;
 }

 public integer getage() {
 return this.age;
 }

 protected void setage(final integer age) {
 this.age = age;
 }
}

@tostring

把所有类属性都编写到tostring方法中方便打印日志,是一件多么枯燥无味的事情。使用@tostring注解可以自动生成tostring方法,默认会包含所有类属性,使用@tostring.exclude注解可以排除属性的生成。

/**
 * created by macro on 2020/12/17.
 */
@tostring
public class tostringexample {
 @tostring.exclude
 private long id;
 private string name;
 private integer age;
 public tostringexample(long id,string name,integer age){
 this.id =id;
 this.name = name;
 this.age = age;
 }

 public static void main(string[] args) {
 tostringexample example = new tostringexample(1l,"test",20);
 //自动实现tostring方法,输出tostringexample(name=test, age=20)
 system.out.println(example);
 }
}

编译后lombok会生成如下代码。

public class tostringexample {
 private long id;
 private string name;
 private integer age;

 public tostringexample(long id, string name, integer age) {
 this.id = id;
 this.name = name;
 this.age = age;
 }

 public string tostring() {
 return "tostringexample(name=" + this.name + ", age=" + this.age + ")";
 }
}

@equalsandhashcode

使用@equalsandhashcode注解可以自动生成hashcode和equals方法,默认包含所有类属性,使用@equalsandhashcode.exclude可以排除属性的生成。

/**
 * created by macro on 2020/12/17.
 */
@getter
@setter
@equalsandhashcode
public class equalsandhashcodeexample {
 private long id;
 @equalsandhashcode.exclude
 private string name;
 @equalsandhashcode.exclude
 private integer age;

 public static void main(string[] args) {
 equalsandhashcodeexample example1 = new equalsandhashcodeexample();
 example1.setid(1l);
 example1.setname("test");
 example1.setage(20);
 equalsandhashcodeexample example2 = new equalsandhashcodeexample();
 example2.setid(1l);
 //equals方法只对比id,返回true
 system.out.println(example1.equals(example2));
 }
}

编译后lombok会生成如下代码。

public class equalsandhashcodeexample {
 private long id;
 private string name;
 private integer age;

 public equalsandhashcodeexample() {
 }

 public boolean equals(final object o) {
 if (o == this) {
  return true;
 } else if (!(o instanceof equalsandhashcodeexample)) {
  return false;
 } else {
  equalsandhashcodeexample other = (equalsandhashcodeexample)o;
  if (!other.canequal(this)) {
  return false;
  } else {
  object this$id = this.getid();
  object other$id = other.getid();
  if (this$id == null) {
   if (other$id != null) {
   return false;
   }
  } else if (!this$id.equals(other$id)) {
   return false;
  }

  return true;
  }
 }
 }

 protected boolean canequal(final object other) {
 return other instanceof equalsandhashcodeexample;
 }

 public int hashcode() {
 int prime = true;
 int result = 1;
 object $id = this.getid();
 int result = result * 59 + ($id == null ? 43 : $id.hashcode());
 return result;
 }
}

@xxconstructor

使用@xxconstructor注解可以自动生成构造方法,有@noargsconstructor、@requiredargsconstructor和@allargsconstructor三个注解可以使用。

  • @noargsconstructor:生成无参构造函数。
  • @requiredargsconstructor:生成包含必须参数的构造函数,使用@nonnull注解的类属性为必须参数。
  • @allargsconstructor:生成包含所有参数的构造函数。
/**
 * created by macro on 2020/12/17.
 */
@noargsconstructor
@requiredargsconstructor(staticname = "of")
@allargsconstructor
public class constructorexample {
 @nonnull
 private long id;
 private string name;
 private integer age;

 public static void main(string[] args) {
 //无参构造器
 constructorexample example1 = new constructorexample();
 //全部参数构造器
 constructorexample example2 = new constructorexample(1l,"test",20);
 //@nonnull注解的必须参数构造器
 constructorexample example3 = constructorexample.of(1l);
 }
}

编译后lombok会生成如下代码。

public class constructorexample {
 @nonnull
 private long id;
 private string name;
 private integer age;

 public constructorexample() {
 }

 private constructorexample(@nonnull final long id) {
 if (id == null) {
  throw new nullpointerexception("id is marked non-null but is null");
 } else {
  this.id = id;
 }
 }

 public static constructorexample of(@nonnull final long id) {
 return new constructorexample(id);
 }

 public constructorexample(@nonnull final long id, final string name, final integer age) {
 if (id == null) {
  throw new nullpointerexception("id is marked non-null but is null");
 } else {
  this.id = id;
  this.name = name;
  this.age = age;
 }
 }
}

@data

@data是一个方便使用的组合注解,是@tostring、@equalsandhashcode、@getter、@setter和@requiredargsconstructor的组合体。

/**
 * created by macro on 2020/12/17.
 */
@data
public class dataexample {
 @nonnull
 private long id;
 @equalsandhashcode.exclude
 private string name;
 @equalsandhashcode.exclude
 private integer age;

 public static void main(string[] args) {
 //@requiredargsconstructor已生效
 dataexample example1 = new dataexample(1l);
 //@getter @setter已生效
 example1.setname("test");
 example1.setage(20);
 //@tostring已生效
 system.out.println(example1);
 dataexample example2 = new dataexample(1l);
 //@equalsandhashcode已生效
 system.out.println(example1.equals(example2));
 }
}

编译后lombok会生成如下代码。

public class dataexample {
 @nonnull
 private long id;
 private string name;
 private integer age;

 public dataexample(@nonnull final long id) {
 if (id == null) {
  throw new nullpointerexception("id is marked non-null but is null");
 } else {
  this.id = id;
 }
 }

 @nonnull
 public long getid() {
 return this.id;
 }

 public string getname() {
 return this.name;
 }

 public integer getage() {
 return this.age;
 }

 public void setid(@nonnull final long id) {
 if (id == null) {
  throw new nullpointerexception("id is marked non-null but is null");
 } else {
  this.id = id;
 }
 }

 public void setname(final string name) {
 this.name = name;
 }

 public void setage(final integer age) {
 this.age = age;
 }

 public boolean equals(final object o) {
 if (o == this) {
  return true;
 } else if (!(o instanceof dataexample)) {
  return false;
 } else {
  dataexample other = (dataexample)o;
  if (!other.canequal(this)) {
  return false;
  } else {
  object this$id = this.getid();
  object other$id = other.getid();
  if (this$id == null) {
   if (other$id != null) {
   return false;
   }
  } else if (!this$id.equals(other$id)) {
   return false;
  }

  return true;
  }
 }
 }

 protected boolean canequal(final object other) {
 return other instanceof dataexample;
 }

 public int hashcode() {
 int prime = true;
 int result = 1;
 object $id = this.getid();
 int result = result * 59 + ($id == null ? 43 : $id.hashcode());
 return result;
 }

 public string tostring() {
 return "dataexample(id=" + this.getid() + ", name=" + this.getname() + ", age=" + this.getage() + ")";
 }
}

@value

使用@value注解可以把类声明为不可变的,声明后此类相当于final类,无法被继承,其属性也会变成final属性。

/**
 * created by macro on 2020/12/17.
 */
@value
public class valueexample {
 private long id;
 private string name;
 private integer age;

 public static void main(string[] args) {
 //只能使用全参构造器
 valueexample example = new valueexample(1l,"test",20);
 // example.setname("andy") //没有生成setter方法,会报错
 // example.name="andy" //字段被设置为final类型,会报错
 }
}

编译后lombok会生成如下代码。

public final class valueexample {
 private final long id;
 private final string name;
 private final integer age;

 public static void main(string[] args) {
 new valueexample(1l, "test", 20);
 }

 public valueexample(final long id, final string name, final integer age) {
 this.id = id;
 this.name = name;
 this.age = age;
 }

 public long getid() {
 return this.id;
 }

 public string getname() {
 return this.name;
 }

 public integer getage() {
 return this.age;
 }
}

@builder

使用@builder注解可以通过建造者模式来创建对象,建造者模式加链式调用,创建对象太方便了!

/**
 * created by macro on 2020/12/17.
 */
@builder
@tostring
public class builderexample {
 private long id;
 private string name;
 private integer age;

 public static void main(string[] args) {
 builderexample example = builderexample.builder()
  .id(1l)
  .name("test")
  .age(20)
  .build();
 system.out.println(example);
 }
}

编译后lombok会生成如下代码。

public class builderexample {
 private long id;
 private string name;
 private integer age;

 builderexample(final long id, final string name, final integer age) {
 this.id = id;
 this.name = name;
 this.age = age;
 }

 public static builderexample.builderexamplebuilder builder() {
 return new builderexample.builderexamplebuilder();
 }

 public string tostring() {
 return "builderexample(id=" + this.id + ", name=" + this.name + ", age=" + this.age + ")";
 }

 public static class builderexamplebuilder {
 private long id;
 private string name;
 private integer age;

 builderexamplebuilder() {
 }

 public builderexample.builderexamplebuilder id(final long id) {
  this.id = id;
  return this;
 }

 public builderexample.builderexamplebuilder name(final string name) {
  this.name = name;
  return this;
 }

 public builderexample.builderexamplebuilder age(final integer age) {
  this.age = age;
  return this;
 }

 public builderexample build() {
  return new builderexample(this.id, this.name, this.age);
 }

 public string tostring() {
  return "builderexample.builderexamplebuilder(id=" + this.id + ", name=" + this.name + ", age=" + this.age + ")";
 }
 }
}

@sneakythrows

还在手动捕获并抛出异常?使用@sneakythrows注解自动实现试试!

/**
 * created by macro on 2020/12/17.
 */
public class sneakythrowsexample {

 //自动抛出异常,无需处理
 @sneakythrows(unsupportedencodingexception.class)
 public static byte[] str2byte(string str){
 return str.getbytes("utf-8");
 }

 public static void main(string[] args) {
 string str = "hello world!";
 system.out.println(str2byte(str).length);
 }
}

编译后lombok会生成如下代码。

public class sneakythrowsexample {
 public sneakythrowsexample() {
 }

 public static byte[] str2byte(string str) {
 try {
  return str.getbytes("utf-8");
 } catch (unsupportedencodingexception var2) {
  throw var2;
 }
 }
}

@synchronized

当我们在多个线程中访问同一资源时,往往会出现线程安全问题,以前我们往往使用synchronized关键字修饰方法来实现同步访问。使用@synchronized注解同样可以实现同步访问。

package com.macro.mall.tiny.example;

import lombok.*;

/**
 * created by macro on 2020/12/17.
 */
@data
public class synchronizedexample {
 @nonnull
 private integer count;

 @synchronized
 @sneakythrows
 public void reducecount(integer id) {
 if (count > 0) {
  thread.sleep(500);
  count--;
  system.out.println(string.format("thread-%d count:%d", id, count));
 }
 }

 public static void main(string[] args) {
 //添加@synchronized三个线程可以同步调用reducecount方法
 synchronizedexample example = new synchronizedexample(20);
 new reducethread(1, example).start();
 new reducethread(2, example).start();
 new reducethread(3, example).start();
 }


 @requiredargsconstructor
 static class reducethread extends thread {
 @nonnull
 private integer id;
 @nonnull
 private synchronizedexample example;

 @override
 public void run() {
  while (example.getcount() > 0) {
  example.reducecount(id);
  }
 }
 }
}

编译后lombok会生成如下代码。

public class synchronizedexample {
 private final object $lock = new object[0];
 @nonnull
 private integer count;

 public void reducecount(integer id) {
 try {
  synchronized(this.$lock) {
  if (this.count > 0) {
   thread.sleep(500l);
   integer var3 = this.count;
   integer var4 = this.count = this.count - 1;
   system.out.println(string.format("thread-%d count:%d", id, this.count));
  }

  }
 } catch (throwable var7) {
  throw var7;
 }
 }
}

@with

使用@with注解可以实现对原对象进行克隆,并改变其一个属性,使用时需要指定全参构造方法。

@with
@allargsconstructor
public class withexample {
 private long id;
 private string name;
 private integer age;

 public static void main(string[] args) {
 withexample example1 = new withexample(1l, "test", 20);
 withexample example2 = example1.withage(22);
 //将原对象进行clone并设置age,返回false
 system.out.println(example1.equals(example2));
 }
}

编译后lombok会生成如下代码。

public class withexample {
 private long id;
 private string name;
 private integer age;

 public withexample withid(final long id) {
 return this.id == id ? this : new withexample(id, this.name, this.age);
 }

 public withexample withname(final string name) {
 return this.name == name ? this : new withexample(this.id, name, this.age);
 }

 public withexample withage(final integer age) {
 return this.age == age ? this : new withexample(this.id, this.name, age);
 }

 public withexample(final long id, final string name, final integer age) {
 this.id = id;
 this.name = name;
 this.age = age;
 }
}

@getter(lazy=true)

当我们获取某一个属性比较消耗资源时,可以给@getter添加 lazy=true 属性实现懒加载,会生成double check lock 样板代码对属性进行懒加载。

/**
 * created by macro on 2020/12/17.
 */
public class getterlazyexample {
 @getter(lazy = true)
 private final double[] cached = expensive();

 private double[] expensive() {
 double[] result = new double[1000000];
 for (int i = 0; i < result.length; i++) {
  result[i] = math.asin(i);
 }
 return result;
 }

 public static void main(string[] args) {
 //使用double check lock 样板代码对属性进行懒加载
 getterlazyexample example = new getterlazyexample();
 system.out.println(example.getcached().length);
 }
}

编译后lombok会生成如下代码。

public class getterlazyexample {
 private final atomicreference<object> cached = new atomicreference();

 public getterlazyexample() {
 }

 private double[] expensive() {
 double[] result = new double[1000000];

 for(int i = 0; i < result.length; ++i) {
  result[i] = math.asin((double)i);
 }

 return result;
 }

 public double[] getcached() {
 object value = this.cached.get();
 if (value == null) {
  synchronized(this.cached) {
  value = this.cached.get();
  if (value == null) {
   double[] actualvalue = this.expensive();
   value = actualvalue == null ? this.cached : actualvalue;
   this.cached.set(value);
  }
  }
 }

 return (double[])((double[])(value == this.cached ? null : value));
 }
}

@log

使用@log注解,可以直接生成日志对象log,通过log对象可以直接打印日志。

/**
 * created by macro on 2020/12/17.
 */
@log
public class logexample {
 public static void main(string[] args) {
 log.info("level info");
 log.warning("level warning");
 log.severe("level severe");
 }
}

编译后lombok会生成如下代码。

public class logexample {
 private static final logger log = logger.getlogger(logexample.class.getname());

 public logexample() {
 }

 public static void main(string[] args) {
 log.info("level info");
 log.warning("level warning");
 log.severe("level severe");
 }
}

@slf4j

使用lombok生成日志对象时,根据使用日志实现的不同,有多种注解可以使用。比如@log、@log4j、@log4j2、@slf4j等。

/**
 * created by macro on 2020/12/17.
 */
@slf4j
public class logslf4jexample {
 public static void main(string[] args) {
 log.info("level:{}","info");
 log.warn("level:{}","warn");
 log.error("level:{}", "error");
 }
}

编译后lombok会生成如下代码。

public class logslf4jexample {
 private static final logger log = loggerfactory.getlogger(logslf4jexample.class);

 public logslf4jexample() {
 }

 public static void main(string[] args) {
 log.info("level:{}", "info");
 log.warn("level:{}", "warn");
 log.error("level:{}", "error");
 }
}

lombok原理

如果idea不安装lombok插件的话,我们打开使用lombok的项目是无法通过编译的。装了以后idea才会提示我们lombok为我们生成的方法和属性。

使用了@data注解以后,查看类结构可以发现getter、setter、tostring等方法。

打开target目录下的 .class 文件,我们可以看到lombok为我们生成的代码,可见lombok是通过解析注解,然后在编译时生成代码来实现java代码的功能增强的。

 

参考资料

官方文档:https://projectlombok.org/features/all

项目源码地址

https://github.com/macrozheng/mall-learning/tree/master/mall-tiny-lombok

到此这篇关于lombok为啥这么牛逼?springboot和idea官方都要支持它的文章就介绍到这了,更多相关lombok springboot和idea内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

《Lombok为啥这么牛逼?SpringBoot和IDEA官方都要支持它.doc》

下载本文的Word格式文档,以方便收藏与打印。