Table of Contents
Lombok
2. Reason for Lombok annotation failure
Integration process
1. Introduce Lombok dependencies:
2. Install the Lombok plug-in
Home Java javaTutorial SpringBoot integrates Lombok and how to solve common problems

SpringBoot integrates Lombok and how to solve common problems

May 20, 2023 pm 12:46 PM
springboot lombok

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!

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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How Springboot integrates Jasypt to implement configuration file encryption How Springboot integrates Jasypt to implement configuration file encryption Jun 01, 2023 am 08:55 AM

Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

Pro Guidance: Expert advice and steps on how to successfully install the Eclipse Lombok plug-in Pro Guidance: Expert advice and steps on how to successfully install the Eclipse Lombok plug-in Jan 28, 2024 am 09:15 AM

Professional guidance: Expert advice and steps for installing the Lombok plug-in in Eclipse, specific code examples are required Summary: Lombok is a Java library that simplifies the writing of Java code through annotations and provides some powerful tools. This article will introduce readers to the steps of how to install and configure the Lombok plug-in in Eclipse, and provide some specific code examples so that readers can better understand and use the Lombok plug-in. Download the Lombok plug-in first, we need

How SpringBoot integrates Redisson to implement delay queue How SpringBoot integrates Redisson to implement delay queue May 30, 2023 pm 02:40 PM

Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick

How to use Redis to implement distributed locks in SpringBoot How to use Redis to implement distributed locks in SpringBoot Jun 03, 2023 am 08:16 AM

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

How to solve the problem that springboot cannot access the file after reading it into a jar package How to solve the problem that springboot cannot access the file after reading it into a jar package Jun 03, 2023 pm 04:38 PM

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables Jun 02, 2023 am 11:07 AM

When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

How SpringBoot customizes Redis to implement cache serialization How SpringBoot customizes Redis to implement cache serialization Jun 03, 2023 am 11:32 AM

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

See all articles