Home > Java > javaTutorial > body text

SpringBoot integrates Lombok and how to solve common problems

PHPz
Release: 2023-05-20 12:46:23
forward
2422 people have browsed it

Lombok

Using annotations allows Lombok to simplify Java code and improve development efficiency. It is an excellent Java code library in itself. It uses an opportunistic syntax sugar to simplify Java coding and provides a way to streamline Java code. However, Lombok is not a standard Java library.

In the process of web development, Java classes that often need to be written require time to add corresponding getter/setter, constructor, equals and other methods. When there are many attributes, there will be a large number of getter/setter methods, which are very lengthy and do not have much technical content. Once the attributes are modified, it is easy to forget to modify the corresponding methods.

SpringBoot integrates Lombok and how to solve common problems

Official website: Project Lombok

1. Commonly used annotations for Lombok

##AnnotationsFunction@Data is annotated on the class; it provides the getting and setting methods for all attributes of the class, and also provides equals, canEqual, hashCode, toString methods@Setter are annotated on the properties; provide setting methods for properties##@Setter @Log4j@NoArgsConstructor@ AllArgsConstructor##@Cleanup:Close the stream@BuilderThe annotated class adds constructor mode@SynchronizedSynchronization lock@SneakyThrowsCatch exceptions, similar to try/catch to catch exceptions@NonNullAdd this annotation to the parameters, When the parameter is null, a null pointer exception will be thrown. @Value annotation is similar to @Data. By default, all member variables are defined as private final modifications and no set method is generated.

SpringBoot integrates Lombok and how to solve common problems

2. Reason for Lombok annotation failure

After introducing Lombok dependency in pom.xml, you also need toinstall the Lombok plug-in,restart IDEA can take effect.

Integration process

1. Introduce Lombok dependencies:

Copy the following code and insert it into pom.xml, wait for the maven warehouse to automatically download and install the dependencies, and there is no automatic package import click Import manually.

<!--导入lombok小辣椒驱动依赖,用来生成get/set等方法依赖-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <!--<optional>true</optional>-->
            <version>1.18.12</version>
            <scope>provided</scope><!--自动生成有参无参构造-->
        </dependency>
Copy after login

SpringBoot integrates Lombok and how to solve common problems

SpringBoot integrates Lombok and how to solve common problems

2. Install the Lombok plug-in

Click File-》Setting-》Plugins-》Search in IDEA After Lombok installs the plug-in, restart IDEA;

SpringBoot integrates Lombok and how to solve common problems

3. Use Lombok to generate getter/setter and other method program code examples for properties

a. Not written using Lombok Entity class (the program is fat and ugly)

Use the shortcut keys that come with the IDE to automatically generate getter/setter methods:

SpringBoot integrates Lombok and how to solve common problems##

package com.dvms.entity;

/*
 *文件名: Anglerecord
 *创建者: CJW
 *创建时间:2020/6/6 14:40
 *描述: 记录
 */
public class Record {

    private String time;
    private String device;
    private String state;

    public Record(String time, String device, String state) {
        this.time = time;
        this.device = device;
        this.state = state;
    }

    public Record() {
    }

    public String getTime() {
        return this.time;
    }

    public String getDevice() {
        return this.device;
    }

    public String getState() {
        return this.state;
    }

    public Record setTime(String time) {
        this.time = time;
        return this;
    }

    public Record setDevice(String device) {
        this.device = device;
        return this;
    }

    public Record setState(String state) {
        this.state = state;
        return this;
    }

    public boolean equals(final Object o) {
        if (o == this) return true;
        if (!(o instanceof Record)) return false;
        final Record other = (Record) o;
        if (!other.canEqual((Object) this)) return false;
        final Object this$time = this.getTime();
        final Object other$time = other.getTime();
        if (this$time == null ? other$time != null : !this$time.equals(other$time)) return false;
        final Object this$device = this.getDevice();
        final Object other$device = other.getDevice();
        if (this$device == null ? other$device != null : !this$device.equals(other$device)) return false;
        final Object this$state = this.getState();
        final Object other$state = other.getState();
        if (this$state == null ? other$state != null : !this$state.equals(other$state)) return false;
        return true;
    }

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

    public int hashCode() {
        final int PRIME = 59;
        int result = 1;
        final Object $time = this.getTime();
        result = result * PRIME + ($time == null ? 43 : $time.hashCode());
        final Object $device = this.getDevice();
        result = result * PRIME + ($device == null ? 43 : $device.hashCode());
        final Object $state = this.getState();
        result = result * PRIME + ($state == null ? 43 : $state.hashCode());
        return result;
    }

    public String toString() {
        return "Record(time=" + this.getTime() + ", device=" + this.getDevice() + ", state=" + this.getState() + ")";
    }
}
Copy after login

b. Introduction Lombok generation method (the program is slim and looks very comfortable)

You can manually add annotations according to your needs, or you can right-click-》Refactor-》Lomok-》

SpringBoot integrates Lombok and how to solve common problems

package com.dvms.entity;

/*
 *文件名: Anglerecord
 *创建者: CJW
 *创建时间:2020/6/6 14:40
 *描述: 记录
 */

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import lombok.experimental.Accessors;

@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true) //链式调用
public class Record {

    private String time;
    private String device;
    private String state;
}
Copy after login

Advantages and disadvantages (possible problems are solutions)

Advantages:

Lombok can automatically generate getter/setter, equals, toString and other methods for properties at compile time through annotations. , eliminating the trouble of manually rebuilding these codes, making the program entity class (entity/pojo) code look more "slim" and more stylish.

Disadvantages (possible problems):

If it is personal development, the following problems may occur:

1.Lombok currently supports JDK1.8, which may become invalid after upgrading the JDK version. Solve Method:

a. Use the Alt Insert shortcut key that comes with the IDE to generate getter/setter, equals, hashCode, toString and constructor methods;

SpringBoot integrates Lombok and how to solve common problems

In the latest version DeLombok can be used to generate these methods using this tool. Right-click and select Refactored->DeLombok:

SpringBoot integrates Lombok and how to solve common problems

Or use a command:

java -jar lombok.jar delombok src -d src-delomboked
Copy after login
Convert the class file implemented by Lombok annotation to a Java source that does not use Lombok document.

Using Lombok can simplify JavaBean encapsulation, but it will affect readability. In addition, try not to use this annotation @AllArgsConstructor. This annotation provides a giant constructor, which gives the outside world the opportunity to modify all the properties in the class when initializing the object. It is very unsafe. After all, some properties of objects in Java classes should not be Revise. At the same time, if there are multiple properties in a Java class, Lombok will inject multiple parameter constructors into the Java class, and the order of the constructor parameters is completely controlled by Lombok.

3. After using Lombok to write Javabean code, other codes that rely on this javabean need to introduce Lombok dependencies, and the code coupling degree increases. At the same time, you also need to install the Lombok plug-in in the IDE.

4. If it is collaborative development, you need to pay attention to the following issues:

When the Lombok plug-in is introduced into our program code, other people must also download and introduce the Lombok plug-in, otherwise the Java code may not work properly run.

Annotate on the attribute; provide a getting method for the attribute
Annotate on the class; provide an attribute named log for the class log4j log object
is annotated on the class; provides a parameterless constructor for the class
Annotated on the class; provides a fully parameterized constructor method for the class

The above is the detailed content of SpringBoot integrates Lombok and how to solve common problems. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template