SpringBoot 优雅编码之: Lombok 加持

2018-04-09 07:19:54 +08:00
 hansonwang99


概述

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


IntelliJ IDEA 上配置

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

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


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

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

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

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

Lombok 主要注解

下文就 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 注解的集成,因此使用很方便!

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;
  }
}
@Data
public class UserLombok {
    private final String name;
    private int age;
    private double score;
    private String[] tags;
}

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

    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 ”;
    }
}

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


后记

更多关于 SpringBoot 的文章:


4595 次点击
所在节点    推广
28 条回复
mgcnrx11
2018-04-09 10:06:18 +08:00
说到 kotlin 在 eclipse 不用装插件一样(逃
night98
2018-04-09 10:10:25 +08:00
还可以用 groove 写 pojo,哈哈,也不用写 get set 方法,maven 加入依赖即可编译运行,idea 自动支持。
paragon
2018-04-09 10:11:57 +08:00
@neoblackcap 无法同意得更多 其实不装插件也不会影响编译打包的~
laodao1990
2018-04-09 12:55:41 +08:00
上次有人推广这玩意就有人吵起来了,可以翻翻 v2
woscaizi
2018-04-09 14:42:59 +08:00
用过一阵子,后来还是老老实实的写 getter and setter 了,毕竟不能保证每个开发者都安装 lombok 插件。
jorneyr
2018-04-09 21:55:35 +08:00
我们在环境搭建的文档里已经要求安装 Lombok 插件,就是一个文档规范的问题,写清楚环境搭建的流程,照文档都不好好做的话,还能有啥期望。
Klingon
2018-04-10 10:34:49 +08:00
已经在老老实实写 getter setter,[逃]
jack80342
2018-04-26 15:15:19 +08:00
这几天翻译了最新的 Spring boot 官方文档,https://www.gitbook.com/book/jack80342/spring-boot/details

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/445226

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX