java lombok 视频_Java开发神器Lombok使用详解

最近正在写SpringBoot系列文章和录制视频教程,每次都要重复写一些Getter/Setter、构造器方法、字符串输出的ToString方法和Equals/HashCode方法等。甚是浪费时间,也影响代码的可读性。因此,今天就给大家推荐一款Java开发神器——Lombok,让代码更简单易读。

什么是Lombok

Lombok是一款Java开发插件,可以通过它定义的注解来精简冗长和繁琐的代码,主要针对简单的Java模型对象(POJO)。

好处就显而易见了,可以节省大量重复工作,特别是当POJO类的属性增减时,需要重复修改的Getter/Setter、构造器方法、equals方法和toString方法等。

而且Lombok针对这些内容的处理是在编译期,而不是通过反射机制,这样的好处是并不会降低系统的性能。

下面我们就看看具体的使用。

Lombok的安装

Lombok的安装分两部分:Idea插件的安装和maven中pom文件的导入。

第一步,在Idea的插件配置中搜索Lombok或官网下载本地安装。

e60f6c16c197575a44b71112d6b1409d.png

同时,在插件的描述中也能够看到它支持的注解。

第二步,引入pom中依赖,当前最细版本1.18.10。

org.projectlombok

lombok

1.18.10

如果是通过Idea创建Spring Boot项目,可在创建项目时直接在“Developer Tool”中选择Lombok。

完成了以上两步,就可以在代码中使用该款神器了。

Lombok的使用

@Data

@Data最常用的注解之一。注解在类上,提供该类所有属性的getter/setter方法,还提供了equals、canEqual、hashCode、toString方法。

这里的提供什么意思?就是开发人员不用手写相应的方法,而Lombok会帮你生成。

使用@Data示例如下,最直观的就是不用写getter/setter方法。

@Data

public class Demo {

private int id;

private String remark;

}

我们看该类编译之后是什么样子。

public class Demo {

private int id;

private String remark;

public Demo() {

}

public int getId() {

return this.id;

}

public String getRemark() {

return this.remark;

}

public void setId(final int id) {

this.id = id;

}

public void setRemark(final String remark) {

this.remark = remark;

}

public boolean equals(final Object o) {

if (o == this) {

return true;

} else if (!(o instanceof Demo)) {

return false;

} else {

Demo other = (Demo)o;

if (!other.canEqual(this)) {

return false;

} else if (this.getId() != other.getId()) {

return false;

} else {

Object this$remark = this.getRemark();

Object other$remark = other.getRemark();

if (this$remark == null) {

if (other$remark != null) {

return false;

}

} else if (!this$remark.equals(other$remark)) {

return false;

}

return true;

}

}

}

protected boolean canEqual(final Object other) {

return other instanceof Demo;

}

public int hashCode() {

int PRIME = true;

int result = 1;

int result = result * 59 this.getId();

Object $remark = this.getRemark();

result = result * 59 ($remark == null ? 43 : $remark.hashCode());

return result;

}

public String toString() {

return "Demo(id=" this.getId() ", remark=" this.getRemark() ")";

}

}

上面的反编译代码,我们可以看到提供了默认的构造方法、属性的getter/setter方法、equals、canEqual、hashCode、toString方法。

使用起来是不是很方便,最关键的是,当新增属性或减少属性时,直接删除属性定义即可,效率是否提升了很多?

为了节省篇幅,后面相关注解我们就不再看反编译的效果了,大家使用idea直接打开编译之后对应的.class文件即可看到。

@Setter

作用于属性上,为该属性提供setter方法; 作用与类上,为该类所有的属性提供setter方法, 都提供默认构造方法。

public class Demo {

private int id;

@Setter

private String remark;

}

@Setter

public class Demo {

private int id;

private String remark;

}

@Getter

基本使用同@Setter方法,不过提供的是getter方法,不再赘述。

@Log4j

作用于类上,为该类提供一个属性名为log的log4j日志对象。

@Log4j

public class Demo {

}

该属性一般使用于Controller、Service等业务处理类上。与此注解相同的还有@Log4j2,顾名思义,针对Log4j2。

@AllArgsConstructor

作用于类上,为该类提供一个包含全部参的构造方法,注意此时默认构造方法不会提供。

@AllArgsConstructor

public class Demo {

private int id;

private String remark;

}

效果如下:

public class Demo {

private int id;

private String remark;

public Demo(final int id, final String remark) {

this.id = id;

this.remark = remark;

}

}

@NoArgsConstructor

作用于类上,提供一个无参的构造方法。可以和@AllArgsConstructor同时使用,此时会生成两个构造方法:无参构造方法和全参构造方法。

@EqualsAndHashCode

作用于类上,生成equals、canEqual、hashCode方法。具体效果参看最开始的@Data效果。

@NonNull

作用于属性上,提供关于此参数的非空检查,如果参数为空,则抛出空指针异常。

使用方法:

public class Demo {

@NonNull

private int id;

private String remark;

}

效果如下:

public class Demo {

@NonNull

private int id;

private String remark;

}

@RequiredArgsConstructor

作用于类上,由类中所有带有@NonNull注解或者带有final修饰的成员变量作为参数生成构造方法。

@Cleanup

作用于变量,保证该变量代表的资源会被自动关闭,默认调用资源的close()方法,如果该资源有其它关闭方法,可使用

@Cleanup(“methodName”)来指定。

public void jedisExample(String[] args) {

try {

@Cleanup Jedis jedis = redisService.getJedis();

} catch (Exception ex) {

logger.error(“Jedis异常:”,ex)

}

}

效果相当于:

public void jedisExample(String[] args) {

Jedis jedis= null;

try {

jedis = redisService.getJedis();

} catch (Exception e) {

logger.error(“Jedis异常:”,ex)

} finally {

if (jedis != null) {

try {

jedis.close();

} catch (Exception e) {

e.printStackTrace();

}

}

}

}

@ToString

作用于类上,生成包含所有参数的toString方法。见@Data中toString方法。

@Value

作用于类上,会生成全参数的构造方法、getter方法、equals、hashCode、toString方法。与@Data相比多了全参构造方法,少了默认构造方法、setter方法和canEqual方法。

该注解需要注意的是:会将字段添加上final修饰,个人感觉此处有些失控,不太建议使用。

@SneakyThrows

作用于方法上,相当于把方法内的代码添加了一个try-catch处理,捕获异常catch中用Lombok.sneakyThrow(e)抛出异常。使用@SneakyThrows(BizException.class)指定抛出具体异常。

@SneakyThrows

public int getValue(){

int a = 1;

int b = 0;

return a/b;

}

效果如下:

public int getValue() {

try {

int a = 1;

int b = 0;

return a / b;

} catch (Throwable var3) {

throw var3;

}

}

@Synchronized

作用于类方法或实例方法上,效果与synchronized相同。区别在于锁对象不同,对于类方法和实例方法,synchronized关键字的锁对象分别是类的class对象和this对象,而@Synchronized的锁对象分别是私有静态final对象lock和私有final对象lock。也可以指定锁对象。

public class FooExample {

private final Object readLock = new Object();

@Synchronized

public static void hello() {

System.out.println("world");

}

@Synchronized("readLock")

public void foo() {

System.out.println("bar");

}

}

效果相当于如下:

public class FooExample {

private static final Object $LOCK = new Object[0];

private final Object readLock = new Object();

public static void hello() {

synchronized($LOCK) {

System.out.println("world");

}

}

public void foo() {

synchronized(readLock) {

System.out.println("bar");

}

}

}

val

使用val作为局部变量声明的类型,而不是实际写入类型。 执行此操作时,将从初始化表达式推断出类型。

public Map getMap() {

val map = new HashMap();

map.put("1", "a");

return map;

}

效果如下:

public Map getMap() {

HashMap map = new HashMap();

map.put("1", "a");

return map;

}

也就是说在局部变量中,Lombok帮你推断出具体的类型,但只能用于局部变量中。

@Builder

作用于类上,如果你喜欢使用Builder的流式操作,那么@Builder可能是你喜欢的注解了。

使用方法:

@Builder

public class Demo {

private int id;

private String remark;

}

效果如下:

public class Demo {

private int id;

private String remark;

Demo(final int id, final String remark) {

this.id = id;

this.remark = remark;

}

public static Demo.DemoBuilder builder() {

return new Demo.DemoBuilder();

}

public static class DemoBuilder {

private int id;

private String remark;

DemoBuilder() {

}

public Demo.DemoBuilder id(final int id) {

this.id = id;

return this;

}

public Demo.DemoBuilder remark(final String remark) {

this.remark = remark;

return this;

}

public Demo build() {

return new Demo(this.id, this.remark);

}

public String toString() {

return "Demo.DemoBuilder(id=" this.id ", remark=" this.remark ")";

}

}

}

我们可以看到,在该类内部提供了DemoBuilder类用来处理具体的流式操作。同时提供了全参的构造方法。

小结

最后,说一下个人的看法,此神器虽然好用,但也不建议大家无条件的使用,为了程序的效率等问题,该自己亲手写的代码还是要自己亲手写。毕竟,只有定制化的才能达到最优化和最符合当前场景。

到此这篇关于Java开发神器Lombok使用详解的文章就介绍到这了,更多相关Java Lombok使用内容请搜索龙方网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持龙方网络!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/369643.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

11-[函数进阶]-闭包

1.什么是闭包? 内部函数对外部函数作用域里变量的引用(非全局变量),则称内部函数为闭包。 def outer():n 10def inner():print("inner:", n)return innerval outer() print(val) val() 闭包的意义:返回的…

Java应该是更高级别还是更低级别?

总览 Java 8带来了许多简化的功能,例如Lambda表达式, 类型注释和虚拟扩展 。 尽管此功能很重要:a)有价值,b)赶上较凉的语言,但是这些更丰富,更高级的功能是Java应当重点关注的领域。…

django开发者模式中的autoreload是怎样实现的

在开发django应用的过程中,使用开发者模式启动服务是特别方便的一件事,只需要 python manage.py runserver 就可以运行服务,并且提供了非常人性化的autoreload机制,不需要手动重启程序就可以修改代码并看到反馈。刚接触的时候觉得…

html5与css3入门知识点精炼

<meta name "keywords" content"…………"/>&#xff08;网页搜索时要输入的关键字&#xff09;<meta name "author" content "作者的名字"<meta http-equiv "refresh" content "跳转的时间 ; URL跳转…

CSS实现单行、多行文本溢出显示省略号(…)

如果实现单行文本的溢出显示省略号同学们应该都知道用text-overflow:ellipsis属性来&#xff0c;当然还需要加宽度width属来兼容部分浏览。 实现方法&#xff1a; overflow: hidden; text-overflow:ellipsis; white-space: nowrap; 效果如图&#xff1a; 但是这个属性只支持单行…

java的方法是什么用,Java中的本机方法是什么?它们应该在何处使用?

A native method has the same syntax as an abstract method, but where is it implemented?解决方案What are native methods in Java and where should they be used?Once you see a small example, it becomes clear:Main.java:public class Main {public native int int…

JAXB –表示空集合和空集合

示范代码 以下演示代码将用于Java模型的所有不同版本。 它只是将一个集合设置为null&#xff0c;第二个设置为空列表&#xff0c;第三个设置为填充列表。 package package blog.xmlelementwrapper;import java.util.ArrayList; import javax.xml.bind.*;public class Demo {pu…

显示日历的指令:cal

1.显示日历的指令&#xff1a;cal &#xff08;1&#xff09;参数&#xff1a; &#xff08;2&#xff09;实例&#xff1a; 转载于:https://www.cnblogs.com/yfacesclub/p/8434449.html

简单好用的计算器:bc

1.简单好用的计算器&#xff1a;bc &#xff08;1&#xff09;参数&#xff1a; &#xff08;2&#xff09;实例&#xff1a; 执行浮点运算和一些高级函数 设定小数精度&#xff08;数值范围&#xff09; 进制转换 执行结果为&#xff1a;11000000&#xff0c;这是用bc将十进制…

Day2 第一次写python

写代码只要会Cpython就可以了Java虚拟机即可执行python代码对于Java代码 也会生成中间代码 做成虚拟机 pypy python代码 先变成字节码 再变成机器码 计算机即可识别 pypy&#xff1a;直接把代码转换成机器码 2.7 可以不加加括号3.6 一定要写括号 #&#xff01;/user/bin/python…

java注解类型命名_第三十九条:注解优先于命名模式

根据经验&#xff0c;一般使用命令模式表明有些程序元素需要通过某种工具或者框架进行特殊处理。例如&#xff0c;在Java4发行版本之前&#xff0c;JUnit测试框架原本要求用户一定要用test作为测试方法名称的开头。这种方法可行&#xff0c;但是有几个很严重的缺点。首先&#…

查看Servlet 3.0的新增功能

随着JEE6规范上市&#xff0c;在企业应用程序领域中如何开发应用程序方面发生了一些重大变化。 在本文中&#xff0c;我将介绍有关Web应用程序开发的一些更改。 首先&#xff0c;请告别web.xml部署描述符&#xff08;至少是其中的一部分&#xff09;。 好吧&#xff0c;它并不是…

block,inline,inline-block的区别

最近正在复习&#xff0c;紧张地准备几天后的笔试&#xff0c;然后刚好看到这个地方。 block&#xff1a;块级元素&#xff0c;会换行&#xff0c;如div,p,h1~h6,table这些&#xff0c;可以设置宽高&#xff1b; inline:行内元素&#xff0c;不换行&#xff0c;挤在一行显示&am…

假期(模块相关)

# ---------------------------------------------------------------------------------------- import time timestamp time.time() #时间戳 struct_time time.localtime() #结构化时间 format_time time.strftime("%Y-%m-%d %X") #格式化时间# print…

anyproxy抓取移动http、https请求

windows下安装AnyProxy抓取移动App Http请求AnyProxy是阿里巴巴基于 Node.js 开发的一款开源代理服务器。做为中间代理服务器&#xff0c;它可以收集所有经过它的http请求流量&#xff08;包括https明文内容&#xff09;&#xff1b;它提供了友好的web界面&#xff0c;便于直观…

振作起来– Spring Framework 4.0即将来临!

几天前&#xff0c;SpringSource 宣布流行的Spring框架的4.0版本正在开发中。 下一个迭代将是Spring Framework 4.0&#xff01; 如SpringSource所言&#xff0c;即将发布的版本的重点是“ 2013年及以后出现的企业主题”&#xff1a; 支持Java SE 8 Spring应用程序 使用Groo…

java内存管理课程设计_Java内存管理分析

Java内存主要分为stack, heap, data segment, and code segment.stack(栈)&#xff1a;存放非静态基本数据类型变量的名称和值&#xff0c;以及非静态对象的引用若是非静态基本数据类型变量&#xff0c;则变量的名称和值一起被存入stack(栈)中&#xff0c;变量的名称指向变量的…

Windows 10 IoT Core 17101 for Insider 版本更新

除夕夜&#xff0c;微软发布了Windows 10 IoT Core 17101 for Insider 版本更新&#xff0c;本次更新只修正了一些Bug&#xff0c;没有发布新的特性。已知的问题: F5 driver deployment from Visual Studio does not work on IoT Core.F5 application deployment of headed f…

Spring Batch中的块处理

大数据集的处理是软件世界中最重要的问题之一。 Spring Batch是一个轻量级且强大的批处理框架&#xff0c;用于处理数据集。 Spring Batch Framework提供了“面向TaskletStep”和“面向块”的处理风格。 在本文中&#xff0c;将解释面向块的处理模型。 此外&#xff0c;绝对建…