We know that when we first learned Java we had to write getters, setters toString….. by hand when we wrote poJO classes Java development tool IDEA also provides these shortcut keys that can generate the getter,setter,toString and other methods corresponding to attributes in one key. However, even if we need to manually generate them every time, it is also very tedious and unfriendly. And when you have a lot of properties in an entity class you get a lot of getters, setter method code that’s not very readable, and that’s why Java sometimes gets bloated, but what’s the solution, Lombok

A simple introduction

Click here to go to lombok’s official website as Lombok describes it

Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java. Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.

Project Lombok is a Java library that automatically plugs into your editor and builds tools to spice up your Java. Never write another getter or equals method. With a comment, your class has a fully functional builder that automates your log variables and so on.

In a nutshell: Lombok makes it easy to annotate Java template code — code that doesn’t have the nutrition to write. Methods like getters, setters, equals, Hashcode, toString, etc. defined in entities). The introduction of logger in logging, etc., is to improve the Java developers, development efficiency of syntax sugar!! 😄, using this post Java development can also be sweet,

Lombok GitHub fierce 👇 here

How do I use Lombok

In the project we will add Lombok dependencies using Maven as an example

<! -- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.20</version>
    <scope>provided</scope>
</dependency>

Copy the code

Using the Lombok plug-in in the IDEA development tool You need to install the Lombok plug-in in the IDEA development tool

  1. Search for Lombok plug-ins by opening the Idea preferences find plug-ins TAB

If not, click Install. I already have it installed, so I need to update it

  1. After the installation, click on the application – idea will take effect after restart

  1. Enable Enable Annotation Processing

At this point you can happily use it in your project

Commonly used annotations

Entity class pojo

@Getter/@Setter

Annotations can be used on both properties and classes, providing getXxx and setXxx methods for individual properties of the entity class when the annotation is on a property and getXxx and setXxx methods for all properties of the class when the annotation is on a class to get and set values for the property

@ToString

The annotation implements the toString() method on the class to print the object’s content, not its address

@EqualsAndHashCode

The annotation implements equals() and hashCode() methods on the class for direct object comparison

@Data

Annotations provide getXxx and setXxx methods on a class for all attributes of the class, as well as equals, canEqual, hashCode, and toString methods

@NoArgsConstructor

An annotation provides a parameterless constructor for a class on a class

The compiler raises an error if a class has a final field that has not been initialized, using @noargsconstructor (force = true) and setting default values 0 / false/null for final fields that have not been initialized. No checks or assignments are generated for fields with constraints (such as the @nonNULL field), so note that the constraints are invalid until these fields are properly initialized.

@AllArgsConstructor

Annotations provide a full-parameter constructor for a class on a class

The default generated method is public, and you can set the value of AccessLevel if you want to change the method modifier. (such as @ AllArgsConstructor access = AccessLevel. PROTECTED)

@RequiredArgsConstructor

Annotations on a class generate a constructor (which may or may not take arguments)

If there are arguments, they can only be final uninitialized fields or @nonNULL uninitialized fields.

The annotation can also generate a static method with the specified name in the form of @requiredargsconstructor (staticName=”methodName”) that returns an object generated by calling the corresponding constructor

@Builder

Annotations implement a Builder Patterns on a class in much the same way that function chain assignment calls such as

Other beans

@Slf4j/@Log4j2

Annotations provide a log object on a class with a property called log and the user improves logging for the class

@Synchronized

The ability to annotate a method to synchronize snippets is that the method executes synchronously

@SneakyThrows

Annotations to methods can be implemented in the try… The throw operation performed after an exception is caught

Click on the official website for more detailed notes

Template code examples

Pojo class

package cn.soboys.springbootmybatisplus.bean;

import lombok.*;

import java.io.Serializable;

/ * * *@author kenx
 * @version 1.0
 * @date2021/6/29 10:03 * /

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@EqualsAndHashCode
@ToString
@Builder
public class User  implements Serializable {
    private static final long serialVersionUID = 6308315887056661996L;
    private String username;
    private int age;
    private String phone;
    private String addr;
}

Copy the code

test

 @Test
    public void t(a) {

        //// Generic pattern builds objects
        User u1 = new User();
        u1.setUsername("keawe");

        // Build the object
        User u = User.builder().build();
        u.setUsername("kenx");

        User user = User.builder()
                .age(18).username("kennx").phone("12313241").addr("232").build();

        // full parameter construction
        // Note that Lombok provides full-parameter constructs that rely on attributes to define the order in the object,
        User u2 = new User("judy".12."120198341"."wewe");
        User u3 = new User("judy".12."120198341"."wewe");

        / / use the toString
        System.out.println("toString" + user);
        System.out.println("toString"+u2);

        / / the equals () is used
        System.out.println("equals" + u.equals(user));
        // If the object attributes are exactly the same, it is true
        System.out.println("equals" + u2.equals(u3));
    }
Copy the code

The tests came back normal.

The above comment can be simplified as follows

@AllArgsConstructor
@NoArgsConstructor
@Builder
@Data
public class User  implements Serializable {
    private static final long serialVersionUID = 6308315887056661996L;
    private String username;
    private int age;
    private String phone;
    private String addr;
}

Copy the code

Because it contains @ Data annotation geXxx SetXX, toString, equals, canEqual, hashCode methods us don’t need to write on a separate its annotation

Ordinary class

package cn.soboys.springbootmybatisplus;

import cn.soboys.springbootmybatisplus.bean.User;
import lombok.SneakyThrows;
import lombok.Synchronized;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;


/ * * *@author kenx
 * @version 1.0
 * @date2021/6/29 10:02 * /
@Slf4j
public class LombokTest {
    
    @Test
    @Synchronized
    @SneakyThrows
    public void a(a) {
        log.info("1421121");
        throw new Exception("wew"); }}Copy the code