资讯专栏INFORMATION COLUMN

SpringBoot优雅编码之:Lombok加持

olle / 2304人阅读

摘要:概述通过提供简单的语法注解形式来帮助简化消除一些必须有但显得很臃肿的代码。作用在方法参数上的注解,用于自动生成空值参数检查自动帮我们调用方法。

概述

Lombok 通过提供简单的语法注解形式来帮助简化消除一些必须有但显得很臃肿的 java 代码。典型的是对于 POJO对象的简化(如自动帮我们生成Setter和Getter等),有了Lombok的加持,开发人员可以免去很多重复且臃肿的操作,极大地提高java代码的信噪比,因此我们必须尝试并应用起来!

注: 本文首发于 My 公众号 CodeSheep ,可 长按扫描 下面的 小心心 来订阅 ↓ ↓ ↓

IntelliJ IDEA上配置

方法一:直接在IDEA界面中配置

首先进入Plugins界面:

然后搜索并安装Lombok插件:

最后不要忘了开启Annotation Processors的Enable选项:

上述安装完成以后需要重启IDEA生效!

方法二:手动下载Lombok插件安装

有时由于网络原因,上面方法一这种方式安装失败,因此只能手动下载安装

下载lombok插件:

https://github.com/mplushniko...

Plugins -> Install plugin from disk... 选择下载的zip包安装

重启idea即可

IDE中设置完成以后需要在pom.xml中添加如下所示的lombok依赖才能使用


    org.projectlombok
    lombok
    1.16.16
Lombok主要注解

@Getter and @Setter / 自动为属性提供 Set和Get 方法

@ToString / 该注解的作用是为类自动生成toString()方法

@EqualsAndHashCode / 为对象字段自动生成hashCode和equals实现

@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor / 顾名思义,为类自动生成对应参数的constructor

@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog / 自动为类添加对应的log支持

@Data / 自动为所有字段添加@ToString, @EqualsAndHashCode, @Getter,为非final字段添加@Setter,和@RequiredArgsConstructor,本质上相当于几个注解的综合效果

@NonNull / 自动帮助我们避免空指针。作用在方法参数上的注解,用于自动生成空值参数检查

@Cleanup / 自动帮我们调用close()方法。作用在局部变量上,在作用域结束时会自动调用close方法释放资源

下文就Lombok中用的最为频繁的@Data@Log注解进行代码实战!

@Data注解使用

官网关于@Data注解的解释如下:

All together now: A shortcut for @ToString, @EqualsAndHashCode, @Getter on all fields, @Setter on all non-final fields, and @RequiredArgsConstructor!

不难理解,其可以看成是多个Lombok注解的集成,因此使用很方便!

先来创建一个POJO实体UserLombok,普通的写法如下:

public class UserLombok {
  private final String name;
  private int age;
  private double score;
  private String[] tags;
  
  public UserLombok(String name) {
    this.name = name;
  }
  
  public String getName() {
    return this.name;
  }
  
  void setAge(int age) {
    this.age = age;
  }
  
  public int getAge() {
    return this.age;
  }
  
  public void setScore(double score) {
    this.score = score;
  }
  
  public double getScore() {
    return this.score;
  }
  
  public String[] getTags() {
    return this.tags;
  }
  
  public void setTags(String[] tags) {
    this.tags = tags;
  }
  
  @Override public String toString() {
    return "DataExample(" + this.getName() + ", " + this.getAge() + ", " + this.getScore() + ", " + Arrays.deepToString(this.getTags()) + “)”;
  }
  
  protected boolean canEqual(Object other) {
    return other instanceof DataExample;
  }
  
  @Override public boolean equals(Object o) {
    if (o == this) return true;
    if (!(o instanceof DataExample)) return false;
    DataExample other = (DataExample) o;
    if (!other.canEqual((Object)this)) return false;
    if (this.getName() == null ? other.getName() != null : !this.getName().equals(other.getName())) return false;
    if (this.getAge() != other.getAge()) return false;
    if (Double.compare(this.getScore(), other.getScore()) != 0) return false;
    if (!Arrays.deepEquals(this.getTags(), other.getTags())) return false;
    return true;
  }
  
  @Override public int hashCode() {
    final int PRIME = 59;
    int result = 1;
    final long temp1 = Double.doubleToLongBits(this.getScore());
    result = (result*PRIME) + (this.getName() == null ? 43 : this.getName().hashCode());
    result = (result*PRIME) + this.getAge();
    result = (result*PRIME) + (int)(temp1 ^ (temp1 >>> 32));
    result = (result*PRIME) + Arrays.deepHashCode(this.getTags());
    return result;
  }
}

Lombok加持后,写法可简化为:

@Data
public class UserLombok {
    private final String name;
    private int age;
    private double score;
    private String[] tags;
}

在IDEA中使用时,Lombok的注解会自动补全,如下图所示:

我们来写POJO的测试代码

    public static void main( String[] args ) {
        UserLombok userLombok = new UserLombok("hansonwang99”);
        userLombok.setAge(18);
        String[] array = new String[]{"apple","juice”};
        userLombok.setTags( array );
        userLombok.setScore( 99.0 );
        System.out.println(userLombok);
    }

由下图我们可以看到IDEA依然可以自动为我们补全由Lombok自动生成的代码:

结果打印

由于Lombok为我们自动生成了toString方法,因此对象的打印结果如下:

UserLombok(name=hansonwang99, age=18, score=99.0, tags=[apple, juice])
@Log注解实战

在我的文章 Spring Boot日志框架实践 一文中,我们使用Log4j2来作为日志对象,其写法如下:

@RestController
@RequestMapping("/testlogging”)
public class LoggingTestController {

    private final Logger logger = LogManager.getLogger(this.getClass());

    @GetMapping("/hello”)
    public String hello() {
        for(int i=0;i<10_0000;i++){
            logger.info("info execute index method”);
            logger.warn("warn execute index method”);
            logger.error("error execute index method”);

        }

        return "My First SpringBoot Application”;
    }
}

若改用Lombok后,写法变得更加简洁,我们只需要引入对应的@Log注解即可完成log对象的生成:

@RestController
@RequestMapping("/testloggingwithlombok”)
@Log4j2
public class LoggingTestControllerLombok {

    @GetMapping("/hello”)
    public String hello() {
        for(int i=0;i<10_0000;i++){
            log.info("info execute index method”);
            log.warn("warn execute index method”);
            log.error("error execute index method”);

        }

        return "My First SpringBoot Application”;
    }
}

怎么样,是不是一切都是那么地优雅!

后记

作者更多的原创文章在此,欢迎观赏

My Personal Blog

作者更多的SpringBt实践文章在此:

Spring Boot应用监控实战

SpringBoot应用部署于外置Tomcat容器

ElasticSearch搜索引擎在SpringBt中的实践

初探Kotlin+SpringBoot联合编程

Spring Boot日志框架实践

SpringBoot优雅编码之:Lombok加持

如果有兴趣,也可以抽点时间看看作者一些关于容器化、微服务化方面的文章:

利用K8S技术栈打造个人私有云 连载文章

从一份配置清单详解Nginx服务器配置

Docker容器可视化监控中心搭建

利用ELK搭建Docker容器化应用日志中心

RPC框架实践之:Apache Thrift

RPC框架实践之:Google gRPC

微服务调用链追踪中心搭建

Docker容器跨主机通信

Docker Swarm集群初探

高效编写Dockerfile的几条准则

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/68975.html

相关文章

  • SpringBoot热部署加持

    摘要:概述进行的开发过程中,我们很多时候经常需要重启服务器才能保证修改的源代码文件或者一些诸如的配置文件以及一些静态文件生效,这样耗时又低效。 showImg(https://segmentfault.com/img/remote/1460000015363888); 概述 进行SpringBoot的Web开发过程中,我们很多时候经常需要重启Web服务器才能保证修改的 源代码文件、或者一些...

    ixlei 评论0 收藏0
  • RPC框架实践:Apache Thrift

    摘要:在文章微服务调用链追踪中心搭建一文中模拟出来的调用链就是一个远程调用的例子,只不过这篇文章里是通过这种同步调用方式,利用的是协议在应用层完成的,这种方法虽然奏效,但有时效率并不高。 showImg(https://segmentfault.com/img/remote/1460000014858219); 一、概述 RPC(Remote Procedure Call)即 远程过程调...

    Gilbertat 评论0 收藏0
  • RPC框架实践:Apache Thrift

    摘要:在文章微服务调用链追踪中心搭建一文中模拟出来的调用链就是一个远程调用的例子,只不过这篇文章里是通过这种同步调用方式,利用的是协议在应用层完成的,这种方法虽然奏效,但有时效率并不高。 showImg(https://segmentfault.com/img/remote/1460000014858219); 一、概述 RPC(Remote Procedure Call)即 远程过程调...

    keithxiaoy 评论0 收藏0
  • SpringBoot应用部署于外置Tomcat容器

    摘要:但考虑到实际的情形中,我们的服务器一般是另外部署好了的,有专门的维护方式。此时我们需要剥离掉应用内置的服务器,进而将应用发布并部署到外置的容器之中,本文就实践一下这个。 showImg(https://segmentfault.com/img/remote/1460000015173574); 0x01. 概述 SpringBoot平时我们用的爽歪歪,爽到它自己连Tomcat都自集成...

    draveness 评论0 收藏0

发表评论

0条评论

olle

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<