Spring Boot reduce boilerplate code - Lombok Java library complete guidance

As a developer, we used to create hundreds of classes in a project. These classes are managed to store data and facilitate operations.

Each class can maintain one or more variables and getters, setter methods for these variables, and the toString method to display class variables.

As a result, the class ends up being too long and if we add or remove any variables, the setter, getter, and toString methods need to be updated again.

It is possible to remove this boilerplate code by using the Java Lombok library. The Lombok library generates the setter, getter, and toString methods for you automatically. All we need to do is annotate the class with Lombok annotations.


How to install Lombok in Eclipse IDE

We can install Lombok in any IDE, follow the steps given here https://projectlombok.org/setup/overview

Open eclipse -> Help -> Install New Software and give the https://projectlombok.org/p2 it will show Lombok select it and click finish.


How to Manually installs Lombok in IDE.

Download the Lombok jar from https://projectlombok.org/downloads/lombok.jar

Open the command prompt in the folder where the Lombok jar is present and run the following command "java -jar lombok.jar" or double-click the Jar. It will open the installation wizard like the one below.

Lombok installation using java command

Please provide the path to your IDE by clicking the "Specify Location" button.

Lombok example in spring boot

Once you have provided the path, click the "Install/Update" button. At this step, you will see a pop-up message indicating the installation has been successful.

Lombok successfully installation popup

To verify whether Lombok is installed properly or not, open eclipse and go to help-> About eclipse IDE. Scroll to the bottom and you will see the Lombok version and link.

Lombok installation in eclipse spring boot  Lombok example


Maven dependencies

Add the below dependency to our pom.xml file to use the Lombok feature in our project.


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


Lombok annotations

We will see different available annotations in Lombok to cut the boilerplate code.


Getter and Setter annotations

From the name itself, we can understand that these annotations generate getter and setter methods for fields.

We can use these annotations (@Getter, @Setter) at the field and class levels. The @Getter annotation creates a public getter method, with the name getName() if the field name is "Name."

The @Setter annotation creates a public setter method that returns void and takes one parameter. If the field name is "Name" then the default setter will be setName()


@Getter
@Setter
public class Employee {

  private int id;
  private String name;
  private String address;
  private double currentSalary;
  private LocalDate joinedDate;
  private List < String > skils;

}

Change access level in Getter and Setter

If we want our methods to have different access levels, we can do that using the AccessLevel attributes.


public class Employee {

	@Setter
	@Getter(value = AccessLevel.PROTECTED)
	private int id;	
}


@ToString

The toString() method is overridden by this annotation, and a default implementation is generated for it. By default, the class name and the fields are printed in order, separated by commas. Also, you can exclude some fields from printing by annotating them with @ToString.Exclude.


@ToString
public class Employee {

  private int id;
  private String name;
  private String address;
  private double currentSalary;
  private LocalDate joinedDate;
  private List < String > skils;
  
}


@EqualsAndHashCode

This annotation overrides the equals() and hashCode() methods.

In the overridden equals() and hashcode() methods, all non-static fields were used, and if we want to exclude any of those fields, we can annotate the field with @EqualsAndHashCode.Exclude.


@EqualsAndHashCode
public class Employee {

  private int id;
  private String name;
  private String address;
  private double currentSalary;
  private LocalDate joinedDate;
  private List < String > skils;

}

Lombok Constructors

@NoArgsConstructor

The annotation is used to generate a constructor with no arguments, or it's like a default constructor in Java without any arguments just initialize the variable with default values. It is used when you want to generate a class instance with no arguments passed in the constructor.


@NoArgsConstructor
public class Employee {

	private  int id;
	private String name;
	private String address;
	private double currentSalary;
	private LocalDate joinedDate;
	private List < String > skils;
	
}


@AllArgsConstructor

The annotation generates a parameterized constructor that accepts only one parameter for each field and initializes them using it.


@AllArgsConstructor
public class Employee {

	private  int id;
	private String name;
	private String address;
	private double currentSalary;
	private LocalDate joinedDate;
	private List < String > skils;
	
}


@RequiredArgsConstructor

The annotation generates a parameterized constructor for each field and field marked with @NonNull. Special handling is given to the fields annotated with @NonNull. An explicit null check will be done in the constructor. If the field is null, a NullPointerException is thrown.


@RequiredArgsConstructor
public class Employee {

	private final int id;

	@NonNull
	private String name;
	
	@NonNull
	private String address;
	
	private double salary;
	
	private List < String > skils;
	
}
spring boot Lombok @RequiredArgsConstructor example


@Data

If we add the @Data annotation then we don't have to add @ToString, @Getter, @Setter, @EqualsAndHashCode, and @RequiredArgsConstructor annotations separately. This is because @Data includes all of them into a single annotation.


@Data
public class Employee {

	private  int id;
	private String name;
	private String address;
	private double currentSalary;
	private LocalDate joinedDate;
	private List < String > skils;
	
}
Spring boot java Lombok @Data example

Removing Lombok

We can remove Lombok easily by running the below command which will duplicate the src folder content into src-delomboked folder.

java -jar lombok.jar delombok src -d src-delomboked

To print the delombok transformation of a single Java file directly on the console, use the below command.

java -jar lombok.jar delombok -p filename.java

Let try delombok on the below java file.

@RequiredArgsConstructor
public class Employee {

	private final int id;

	@NonNull
	private String name;
	
	@NonNull
	private String address;
	
	private double salary;
	
	private List < String > skils;
	
}

After running delombok command the class file.


import lombok.NonNull;
import lombok.Setter;
import lombok.ToString;

public class Employee {
  private final int id;
  @NonNull
  private String name;
  @NonNull
  private String address;
  private double salary;
  private List < String > skils;

  @java.lang.SuppressWarnings("all")
  public Employee(final int id, @NonNull final String name, @NonNull final String address) {
    if (name == null) {
      throw new java.lang.NullPointerException("name is marked non-null but is null");
    }
    if (address == null) {
      throw new java.lang.NullPointerException("address is marked non-null but is null");
    }
    this.id = id;
    this.name = name;
    this.address = address;
  }
}


you can see the Lombok annotation is removed and the actual implementation of the annotation is added to the file and printed the console.

spring boot java delombok example command


2 Comments

Previous Post Next Post

Recent Posts

Facebook