SpringBoot整合Lombok简化Java代码

时间:2024-01-26 19:35:50

一、前言

Lombok能以简单的注解形式来简化Java代码,提高开发人员的开发效率。比如我们在开发中经常需要添加实体类的getter/setter方法、equals方法和hashcode方法等。当属性过多的情况下我们需要书写很多的这种代码,造成代码冗长。Lombok能通过注解的方式,在编译时自动为属性生成构造器、getter/setter、equals、hashcode、toString等方法。

二、SpringBoot集成Lombok

1.添加依赖

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

2.常用的Lombok注解

注解

说明

@Getter

生成Getter方法

@Setter

生成Setter方法

@ToString

生成toString方法

@Data

这个注解可以生成getter/setter、equals、hashcode、toString是一个综合的注解

@Slf4j

可以用来生成日志

@Builder

通过建造者模式来创建对象,可以通过链式调用的方式进行对象赋值

@EqualsAndHashCode

生成equals和hashCode方法

@AllArgsConstructor

生成包含所有属性构造器

@NoArgsConstructor

生成一个空构造器

3.@Getter和Setter的使用

package com.example.nettyserverdemo.entity;

import lombok.Getter;
import lombok.Setter;

/**
 * @author qx
 * @date 2024/1/10
 * @des 测试
 */
@Getter
@Setter
public class User {

    private Long id;
    private String name;
    private Integer age;
    
}

我们在实体类上添加@Getter和@Setter注解。字节码文件反编译后的内容是:

package com.example.nettyserverdemo.entity;

public class User {
    private Long id;
    private String name;
    private Integer age;

    public User() {
    }

    public Long getId() {
        return this.id;
    }

    public String getName() {
        return this.name;
    }

    public Integer getAge() {
        return this.age;
    }

    public void setId(final Long id) {
        this.id = id;
    }

    public void setName(final String name) {
        this.name = name;
    }

    public void setAge(final Integer age) {
        this.age = age;
    }
}

发现通过Lombok的注解帮我们自动生成了对应的Getter和Setter方法。

4.ToString

package com.example.nettyserverdemo.entity;

import lombok.ToString;

/**
 * @author qx
 * @date 2024/1/10
 * @des 测试
 */
@ToString
public class User {

    private Long id;
    private String name;
    private Integer age;

}

我们在类上添加@ToString注解,字节码文件反编译后的内容是:

package com.example.nettyserverdemo.entity;

public class User {
    private Long id;
    private String name;
    private Integer age;

    public User() {
    }

    public String toString() {
        return "User(id=" + this.id + ", name=" + this.name + ", age=" + this.age + ")";
    }
}

我们发现通过使用@ToString注解,Lombok自动帮我们生成了toString方法。

5.@Data

package com.example.nettyserverdemo.entity;

import lombok.Data;

/**
 * @author qx
 * @date 2024/1/10
 * @des 测试
 */
@Data
public class User {

    private Long id;
    private String name;
    private Integer age;

}

我们在类上添加@Data注解,字节码文件反编译后的内容是:

package com.example.nettyserverdemo.entity;

public class User {
    private Long id;
    private String name;
    private Integer age;

    public User() {
    }

    public Long getId() {
        return this.id;
    }

    public String getName() {
        return this.name;
    }

    public Integer getAge() {
        return this.age;
    }

    public void setId(final Long id) {
        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 User)) {
            return false;
        } else {
            User other = (User)o;
            if (!other.canEqual(this)) {
                return false;
            } else {
                label47: {
                    Object this$id = this.getId();
                    Object other$id = other.getId();
                    if (this$id == null) {
                        if (other$id == null) {
                            break label47;
                        }
                    } else if (this$id.equals(other$id)) {
                        break label47;
                    }

                    return false;
                }

                Object this$age = this.getAge();
                Object other$age = other.getAge();
                if (this$age == null) {
                    if (other$age != null) {
                        return false;
                    }
                } else if (!this$age.equals(other$age)) {
                    return false;
                }

                Object this$name = this.getName();
                Object other$name = other.getName();
                if (this$name == null) {
                    if (other$name != null) {
                        return false;
                    }
                } else if (!this$name.equals(other$name)) {
                    return false;
                }

                return true;
            }
        }
    }

    protected boolean canEqual(final Object other) {
        return other instanceof User;
    }

    public int hashCode() {
        int PRIME = true;
        int result = 1;
        Object $id = this.getId();
        result = result * 59 + ($id == null ? 43 : $id.hashCode());
        Object $age = this.getAge();
        result = result * 59 + ($age == null ? 43 : $age.hashCode());
        Object $name = this.getName();
        result = result * 59 + ($name == null ? 43 : $name.hashCode());
        return result;
    }

    public String toString() {
        return "User(id=" + this.getId() + ", name=" + this.getName() + ", age=" + this.getAge() + ")";
    }
}

发现我们使用@Data注解后,Lombok自动帮我们生成了Getter/Setter、equals、hashCode和toString方法。

6.@Slf4j

package com.example.nettyserverdemo.entity;

import lombok.extern.slf4j.Slf4j;

/**
 * @author qx
 * @date 2024/1/10
 * @des log4j测试
 */
@Slf4j
public class Log4jDemo {
    public static void main(String[] args) {
        log.info("test:{}", "log4j");
    }
}

我们在类上添加@Slf4j注解,字节码文件反编译后的内容是:

package com.example.nettyserverdemo.entity;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Log4jDemo {
    private static final Logger log = LoggerFactory.getLogger(Log4jDemo.class);

    public Log4jDemo() {
    }

    public static void main(String[] args) {
        log.info("test:{}", "log4j");
    }
}

发现我们使用@Slf4j注解之后,Lombok自动帮我们实例化日志对象。

7.@Builder

package com.example.nettyserverdemo.entity;

import lombok.Builder;
import lombok.Data;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

/**
 * @author qx
 * @date 2024/1/10
 * @des 测试
 */
@Builder
@ToString
public class User {

    private Long id;
    private String name;
    private Integer age;

    public static void main(String[] args) {
        User user = User.builder().id(1L).name("admin").age(20).build();
        System.out.println(user);
    }
}

字节码文件反编译后的内容是:

package com.example.nettyserverdemo.entity;

public class User {
    private Long id;
    private String name;
    private Integer age;

    public static void main(String[] args) {
        User user = builder().id(1L).name("admin").age(20).build();
        System.out.println(user);
    }

    User(final Long id, final String name, final Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public static UserBuilder builder() {
        return new UserBuilder();
    }

    public String toString() {
        return "User(id=" + this.id + ", name=" + this.name + ", age=" + this.age + ")";
    }

    public static class UserBuilder {
        private Long id;
        private String name;
        private Integer age;

        UserBuilder() {
        }

        public UserBuilder id(final Long id) {
            this.id = id;
            return this;
        }

        public UserBuilder name(final String name) {
            this.name = name;
            return this;
        }

        public UserBuilder age(final Integer age) {
            this.age = age;
            return this;
        }

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

        public String toString() {
            return "User.UserBuilder(id=" + this.id + ", name=" + this.name + ", age=" + this.age + ")";
        }
    }
}

8.@AllArgsConstructor和@NoArgsConstructor

package com.example.nettyserverdemo.entity;

import lombok.*;
import lombok.extern.slf4j.Slf4j;

/**
 * @author qx
 * @date 2024/1/10
 * @des 测试
 */
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class User {

    private Long id;
    private String name;
    private Integer age;

}

字节码文件反编译后的内容是:

package com.example.nettyserverdemo.entity;

public class User {
    private Long id;
    private String name;
    private Integer age;

    public Long getId() {
        return this.id;
    }

    public String getName() {
        return this.name;
    }

    public Integer getAge() {
        return this.age;
    }

    public void setId(final Long id) {
        this.id = id;
    }

    public void setName(final String name) {
        this.name = name;
    }

    public void setAge(final Integer age) {
        this.age = age;
    }

    public User() {
    }

    public User(final Long id, final String name, final Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }
}

三、小结

Lombok 是一个流行的 Java 库,旨在通过注解的方式简化 Java 代码,减少模板代码的编写。它通过在编译时自动生成常用的 Java 代码(如 getters、setters、constructors、toString、equals、hashCode 等方法),使得源代码更加简洁。

但是需要团队内部达成一致,就是要用大家都用,否则有些用了有些没用就会乱成一锅粥,很影响代码的整体风格。