# SpringBoot3教程 - 3 Lombok和Hutool

我们在写 Java Bean 的时候,需要编写或生成 getter 和 setter 非常的麻烦,Lombok 就是来解决这个麻烦的。

Lombok 是一个 Java 库,在编译代码的时候,它通过注解自动生成常见的代码结构,如构造器、getter、setter、equals、hashCode、toString 等,从而提高开发效率并使代码更加简洁和易读。

下面介绍一下 Lombok 的使用和常用的注解,后面我们就使用Lombok简化我们的工作。

# 4.1 Lombok的使用

# 1 首先引入依赖

在SpringBoot的项目中,在 pom.xml 中引入依赖:

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
1
2
3
4
5

# 2 安装插件

如果IDEA版本在2020.3以上,不需要安装Lombok插件。如果IDEA 版本在2020.3以下,需要安装Lombok插件。

点击 Flie --> Setting --> Plugins --> 搜索Lombok --> 安装。

# 4.2 Lombok常用注解

# 1 @Getter和@Setter

类上方的 @Getter@Setter 注解会自动为类的属性添加 getter 和 setter 。

import lombok.Getter;
import lombok.Setter;

// 给所有属性添加getter和setter
@Getter 
@Setter
public class User { 
    @Setter  // 给指定的属性添加setter
    private String id;
    @Setter(AccessLevel.PRIVATE)  // 设置setter为私有
    private String name;
    @Getter(AccessLevel.NONE)  // 取消password的getter方法
    private int password;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

可以在类上添加为所有的属性添加 getter 和 setter,也可以为指定的属性添加。

# 2 @ToString

自动生成 toString 方法。

import lombok.ToString;

@ToString
public class User {
    private String id;
    private String name;
    private int age;
}
1
2
3
4
5
6
7
8

还可以排除指定的属性:

import lombok.ToString;

@ToString(exclude = {"password"})
public class User {
    private String id;
    private String name;
    private int age;
}
1
2
3
4
5
6
7
8

# 3 @EqualsAndHashCode

自动生成 equalshashCode 方法。

import lombok.EqualsAndHashCode;

@EqualsAndHashCode
public class User {
    private String id;
    private String name;
    private int age;
}
1
2
3
4
5
6
7
8

# 4 @NonNull

可以添加在属性上,表示使用构造方法或setter给属性赋值时不能为null。

可以添加在方法参数上,传递参数不能为null。

可以添加在方法上,表示返回值不能为null。

import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;

@Setter
@Getter
public class User {
    // 调用构造方法或setter赋值时,值不能为null
    @NonNull
    private String id;
    private String username;
    private String password;

    @NonNull  // 方法返回值不能为null
    public void sing(@NonNull String song) {  // 调用sing方法时,song参数不能为null
        System.out.println("我唱:" + song);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# 5 构造方法注解

@NoArgsConstructor, @RequiredArgsConstructor@AllArgsConstructor 注解用于自动生成构造器。@NoArgsConstructor 生成无参构造器,@RequiredArgsConstructor 生成包含所有 final 字段和带有 @NonNull 注解的字段的构造器,@AllArgsConstructor 生成包含所有字段的构造器。

import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

@NoArgsConstructor
@AllArgsConstructor
public class User {
    private String id;
    private String name;
    private String password;
}
1
2
3
4
5
6
7
8
9
10

# 6 @Data(最常用)

综合了 @Getter@Setter@ToString@EqualsAndHashCode@RequiredArgsConstructor,为类提供全面的功能。

import lombok.Data;

@Data
public class User {
    private String name;
    private int age;
}
1
2
3
4
5
6
7

一般都会在 Bean 上添加该注解,包括与数据库表映射的实体类上。

# 7 @Slf4j(最常用)

自动生成日志记录器字段,支持不同的日志框架(如 SLF4J、Log4j、Logback)。

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class User {
    public void doSomething() {
        log.info("Doing something");
    }
}
1
2
3
4
5
6
7
8

可以在Controller、Service 等组件上添加,用来打印日志,非常方便。

# 8 @Cleanup

@Cleanup 是 Lombok 提供的一个注解,用于简化资源的管理和清理。它确保在方法或代码块执行完毕后,自动调用指定资源的 close() 方法,从而避免资源泄漏。@Cleanup 特别适用于需要显式关闭的资源,如 I/O 流、数据库连接等。

import lombok.Cleanup;
import java.io.*;

public class FileProcessor {
    public void readFile(String path) throws IOException {
        @Cleanup InputStream in = new FileInputStream(path);
        @Cleanup OutputStream out = new FileOutputStream("output.txt");
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

在这个示例中,@Cleanup 确保 inoutreadFile 方法执行完毕后会自动调用它们的 close() 方法。

Lombok 在编译时会生成资源管理的代码。例如,对于上面的 readFile 方法,Lombok 会生成如下的代码:

public void readFile(String path) throws IOException {
    InputStream in = new FileInputStream(path);
    try {
        OutputStream out = new FileOutputStream("output.txt");
        try {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        } finally {
            if (out != null) {
                out.close();
            }
        }
    } finally {
        if (in != null) {
            in.close();
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 4.3 Hutool工具包

Hutool 是一个小而全的Java工具类库,其中包含了各种 Java 的工具类,我们可以拿来就用,提高工作效率。

官网:https://www.hutool.cn/ --> 点击前往 (opens new window)

# 1 引入依赖

在项目的 pom.xml 中使用 Maven 引入依赖。

<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.28</version>
</dependency>
1
2
3
4
5

引入后,右键pom -> Maven -> Reload project

# 2 使用

然后就可以使用了。下面简单演示一下:

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;

import java.util.ArrayList;
import java.util.List;

public class TestClass {
    public static void main(String[] args) {
        String str = "";
        // 判断字符串是否为null或空字符串
        if (StrUtil.isEmpty(str)) {  // true
            System.out.println("字符串为空");
        }

        List<String> list = new ArrayList<>();
        // 判断集合是否为空
        if (CollUtil.isEmpty(list)) {  // true
            System.out.println("集合为空");
        }

        // 获取uuid
        System.out.println(IdUtil.simpleUUID());

        // 获取md5码
        String md5 = DigestUtil.md5Hex("abc");
        System.out.println(md5);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

Hutool 工具包提供了太多的工具了,包括字符串、日期、集合、http、编码等等,可以登录官网查看。