Spring Boot with Lombok

Sandaminimadhushika
3 min readMar 4, 2022

--

What is Lombok?

Project Lombok is a Java library tool that generates code for minimizing boilerplate code. The library replaces boilerplate code with easy-to-use annotations.

For example, by adding a couple of annotations, you can get rid of code clutters, such as getters and setters methods, constructors, hashcode, equals, and toString methods, and so on.

Lombok Dependency

To use Lombok in our project, we have to add it as a dependency in pom.xml file. Lombok dependency is a curated dependency, so you can omit the version.

Lombok annotations

There are many annotations in Lombok. Let’s dive into those annotations with the examples.

You can use the Getter and setter annotations at both the field or class level to generate getters and setters for private fields. The generated getter/setter method will be public by default. Let’s create a model called student.java,

Code without Lombok,

Code with Lombok,

I think you could easily able to figure out the advantage of the Lombok. Lombok Java library tool generates code for minimizing boilerplate code. The library replaces boilerplate code with easy-to-use annotations. Here, we no need to create getters and setters. Lombok annotations provide all these functionalities to our project.

Also we can use Data annotation instead of all above annotations in the code. Data annotation generates all the boilerplate that is normally associated with simple POJOs (Plain Old Java Objects) and beans :
getter methods for all fields, setter methods for all non-final fields,appropriate toString(), appropriate equals() and hashCode() implementations that involve the fields of the class, and a constructor that initializes all final field

Let’s look at about how we can use this Student.java model in our project with the logger functionality. Here, we can use Slf4j annotation which is come from Lombok tool. Boilerplate code can be easily minimized. Here, I use info level log statement to describe the behavior of the Lombok Slf4j annotation.

Code without Lombok,

Code with Lombok,

In both time, we can see the output as follows,

Output image

Also we can use Builder annotation in our code. Project Lombok’s Builder is a helpful mechanism for using the Builder patterns without writing boilerplate code. We can apply this annotation to a Class or a method. Here, we’re merely implementing a the Student Class, and we want to use a builder to create instances of our class.

Code of Student.java with Builder,

Code of creating instance with Builder,

In this brief article, I used Lombok’s annotations to simplify the code. Code samples, as always, can be found over on GitHub. That’s all for this article. Thank you for reading!!

--

--

No responses yet