How to use Project Lombok in Spring Boot

Spring Boot is a popular open source Spring application development framework for Java. Project Lombok helps with creating boilerplate code and provides the ability to write less redundant, easier to read code that you would normally need developers to create from scratch. It can help eliminate errors in your project by providing automatic imports of commonly used modules. This post walks through how it can be configured as well as an example usage scenario of using it with Spring Boot

Project Lombok is a Java library that provides a set of annotations and APIs to simplify the process of writing code. Spring Boot uses Project Lombok by default, so this tutorial will show you how to use it in your own project.

How to use Project Lombok in Spring Boot

You will learn how to utilize the Spring Boot application with project Lombok in this tutorial.

Overview

Without a question, Java is a fantastic language, but one of its downsides is its verbosity. This makes it difficult to do routine activities like constructing a basic POJO object. Constructing methods such as Getters(), Setters(), Constructors(), toString(), and HashCode(), for example.

Despite the fact that most current IDEs can construct these methods automatically, each class still needs user interaction. As a result, this takes a long time. These needless lines of code may be greatly reduced with Lombok. As a result, it saves a lot of time for developers that would otherwise be spent creating boilerplate code. Furthermore, it improves the readability of the code and saves space.

Preparation:

I’ll be utilizing the following tools in this example:

  • JDK 1.8
  • Idea for Intellij IDE
  • Maven
  • Version 2.5.5 of the Springboot application
  • Lombok

For a better understanding, there are two primary phases in this tutorial:

  • Step 1: Example of an Application without Project Lombok
  • Step 2: An example of an application using the Lombok project

We’ll see how a standard spring-boot java class looks without project Lombok in the following stage.

Step 1 – An Example of an Application Without Project Lombok

I constructed a very basic Spring Boot application in this phase. To learn how to develop a very basic Web App using Spring Boot, read this lesson “Create a Simple Web Service Project with Spring Boot.” After importing the project into the IDE, we’ll create a sub-package named ‘Model’ inside our project. After that, we’ll build a POJO file called “BusinessPartner.java.” The entity BusinessPartner is included in this object file, and we will utilize it in our next class.

Finally, the project’s file structure should resemble that seen below.

How-to-use-Project-Lombok-in-Spring-Boot

Our class will now have private member variables. We’ll also build helper methods for each of the four member variables, such as getters(), setters(), and toString().

The following is the code for “BusinessPartner.java”:

package com.appsdeveloperblog.lomboktutorial.model; import java.util.Objects; public class BusinessPartner { private String firstName; private String lastName; private String uid; private String address; public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getUid() { return uid; } public String getAddress() { return address; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public String toString() { return “BusinessPartner{” + “firstName=”” + firstName + “” + “, lastName=”” + lastName + “” + “, uid=’” + uid + ”’ + “, address=”” + address + “” + ‘}’; } public void setUid(String uid) { this.uid = uid; } public void setAddress(String address) { this.address = address; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; BusinessPartner that = (BusinessPartner) o; return Objects.equals(getFirstName(), that.getFirstName()) && Objects.equals(getLastName(), that.getLastName()) && Objects.equals(getUid(), that.getUid()) && Objects.equals(getAddress(), that.getAddress()); } @Override public int hashCode() { return Objects.hash(getFirstName(), getLastName(), getUid(), getAddress()); } }

After that, we’ll make changes to our main application class. We’ll use this method to create our business partner object and fill it with fake data. Finally, we’ll print this object.

Second, copy “MainApplication’s” logic as follows:

package com.appsdeveloperblog.lomboktutorial; import com.appsdeveloperblog.lomboktutorial.model.BusinessPartner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import java.util.logging.Level; import java.util.logging.Logger; @SpringBootApplication public class LomboktutorialApplication { private final static Logger LOGGER = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME); public static void main(String[] args) { SpringApplication.run(LomboktutorialApplication.class, args); BusinessPartner bp = new BusinessPartner(); bp.setFirstName(“Bill”); bp.setLastName(“Mark”); bp.setUid(“BP-U2323”); bp.setAddress(“3/2 New Avenue Road,UK”); LOGGER.log(Level.INFO, “Output is my BP class is —> n”+ bp.toString()); } }

 

If we run our program now, the IDE should display the following output.

2021-09-29 23:25:26.689 INFO 15740 — [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ” 2021-09-29 23:25:26.695 INFO 15740 — [ main] c.a.l.LomboktutorialApplication : Started LomboktutorialApplication in 3.892 seconds (JVM running for 4.772) 2021-09-29 23:25:26.700 INFO 15740 — [ main] global : Output is my BP class is —> BusinessPartner{firstName=”Bill”, lastName=”Mark”, uid=’BP-U2323′, address=”3/2 New Avenue Road,UK”}

So far, everything has gone swimmingly.

However, if we look back at our code development up to this point, we’ll note that our primary object class, BusinessPartner, only contains four private member variables. Despite this, the developer must add almost 70 lines of code to implement supporting auxiliary functions. Assume you’re constructing a production-ready application with a large number of classes. The developer will have to create it for each of the object classes manually. There’s a lot of boilerplate code here, and it’s taking a long time.

In the following phase, we’ll look at ways to improve this.

Step 2 – Project Lombok as an example of an application

To begin using Lombok, we must first make some fundamental settings in our IDE. This may be accomplished as follows:

Using your IDE to enable Lombok

  1. As of version 2020.3, the IntelliJ IDEA IDE is compatible with Lombok without the need for a plugin. You may use the Lombok IntelliJ plugin to add Lombok to previous versions of IntelliJ. Other IDEs may be found at https://projectlombok.org/setup/overview/ and need the installation of the associated plugin.
  2. Enable annotation processing from settings as below. (You can find it inside File -> Settings for Intellij Idea)

 

1633037321_258_How-to-use-Project-Lombok-in-Spring-Boot

 

After that, you must add the Lombok dependent to your pom.xml file.

lombok 1.18.20 org.projectlombok

Our code will be optimized in the following stage.

We’ll go back to our BusinessPartner object class, where our boilerplate code is stored. To begin, we’ll delete all of the methods, such as Getters(), Setters(), Constructors(), toString(), and HashCode, and replace them with annotations as shown below.

(Don’t forget to import lombok.Data; in your class as well.)

@Data public class BusinessPartner private String firstName; private String lastName; private String uid; private String address; package com.appsdeveloperblog.lomboktutorial.model; import lombok.Data; @Data public class BusinessPartner private String firstName; private String lastName; private String uid; private String address;

Our application is now ready to run. As you may have seen, we don’t need to handle our boilerplate code for getter(), setters(), toString(), and so on in new logic. In comparison to previous code, our BusinessPartner object functionality has been reduced to 4+ lines of code from 60+ lines. All @Getter, @Setters, @ToString, and other repetitive code is replaced with a single @Data annotation. This is Lombok’s strength.

In addition, Lombok has a few more useful annotations, which we will discuss in the following section.

Let’s take a look at some of the most often used Lombok Annotations.

    • @AllArgsConstructor: This annotation creates a constructor for each field in your class with one argument.
    • @NoArgsConstructor: This annotation creates a constructor that doesn’t take any arguments.
    • @Data: This is a shortcut annotation that allows you to merge numerous annotations into one. Combine the annotations @Getter, @EqualsAndHashCode, @ToString,[email protected], and @RequiredArgsConstructor, for example.
    • @NonNull: This annotation on a constructor or method argument triggers a null check.
    • @Synchronized is a method annotation that makes Java methods synchronized. This is for the sake of thread safety.
    • @slf4j: This annotation creates a logger object with the name ‘log’ as the default.

Conclusion

In this tutorial, we’ve looked at how the use of Lombok can write better Java code. Additionally, Lombok annotations can considerably reduce the boilerplate code. Also, it makes project development faster plus makes your code clean, clear & easier to read.

Watch This Video-

Project Lombok is a Java library that allows you to write less code. It can be used in Spring Boot applications and provides many benefits, such as: no boilerplate, annotation-driven configuration of dependencies and more. Reference: lombok spring-boot not working.

Frequently Asked Questions

How do you use Lombok in Spring project?

A: Lombok is a static analysis tool for Java projects. You can use it to find unused classes and resources in your project, as well as automatically generate import statements from the class files you have created so far.

What is use of Lombok in spring boot?

A: The Lombok dependency injection framework is used in the Spring Boot Framework.

How do you put a Lombok jar in a spring boot?

  • spring boot lombok example
  • lombok maven dependency spring-boot not working
  • lombokspring boot dependency
  • lombok annotations
  • lombok tutorial
You May Also Like