search
HomeJavajavaTutorialSpringBoot integrates Lombok and how to solve common problems

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>

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() + ")";
    }
}

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

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

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!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.