Writing More Readable Code with Project Lombok
We have written a lot of boilerplate code such as getter, setter, equals, hashCode methods, etc. in Java for years. In some cases, this causes problems in subjects like clean and readable code.
For such situations, Project Lombok saves our eyes :). Also, you will be able to spend more time on the business logic using Lombok.
In this tutorial, I will tell you about Project Lombok and give an example using Spring Boot.
- Spring Boot and Spring Data projects which are used for developing REST APIs are used here.
- Maven is used to automate the build process.
- A typical domain-driven development approach is used, separating model, repository, service, and controller classes.
You can download the project source code from this GitHub link.
What is Project Lombok?
I copied and pasted the description of Project Lombok from here (Official Site). I couldn’t make a better sentence to explain 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 uses annotations to avoid boilerplate code. In the best cases, only five lines can replace hundreds of lines of code.
As you see below, a few annotations were used instead of almost eighty of lines of code.
Descriptions of used annotations according to JavaDoc:
@Data
: “Generates getters for all fields, a useful toString method, and hashCode and equals implementations that check * all non-transient fields. Will also generate setters for all non-final fields, as well as a constructor.”@AllArgsConstructor
: “Generates an all-args constructor.”@NoArgsConstructor
: “Generates a no-args constructor.”@Slf4j
: “Causes Lombok to generate a logger field.”
You can see the Book model below which is created without using Lombok as well.
Project Lombok also provides convenience for logging as follows. For example, you can use the @Slf4j
annotation for logging.
How to Install Lombok
We can integrate Lombok into our IDE (IntelliJ, Eclipse, etc.) easily.
In this section, I will tell you about Lombok installation for IntelliJ Idea. You can click here for other installations.
- Firstly, you must select Lombok while initializing your Spring Boot project like below.
2. After that, if you don’t add Lombok plugin to your IDE before, IntelliJ asks you a question. You must select Lombok plugin and click the Ok button to install plugin in your IDE.
You can verify that Lombok is installed in your IDE like below. As soon as the installation of Lombok is done, we are ready to go.
Library Information System
The tutorial here uses IntelliJ IDEA, Maven, and Postman for coding, building, and REST API testing. I’m running on Windows 10 using PowerShell.
All software is written in Java, with Spring 5.2 and Spring Boot 2.2.2, in-memory H2 database is used for persistence.
From here, I’ll assume you have JDK 13.0, IntelliJ, Maven, and Postman installed.
This library information system brings book information and allows you to add new books to the system or remove books from the system.
My goal here is to show how to use Lombok in a simple way without shuffling the business logic.
- A POST operation is used to add books to the system.
- The book table in the in-memory H2 database has the data about each book’s name, writer, genre and year.
- Everything stored, received, and returned by the service is formatted as JSON.
Book Model
This model has 5 fields: id, name, writer, genre and year.
These used Lombok annotations are explained above.
Book Repository
You can easily create an interface extending CrudRepository using Spring Data Project. With this, there is no need to implement this interface :).
There are four methods in the BookRepository. These are simple CRUD(Create, Read, Update, Delete) operations.
Book Service
The book service has four methods. Simply, these methods list books according to some criteria, save or update a book and delete a book.
You can see the implementation of this interface below.
Book Controller
BookController.java is a REST controller which has two @GetMapping
, one @PostMapping
and one @DeleteMapping
.
Database Configuration
To connect to the H2 database, edit the settings in the “application.properties” file which is part of “resources”. The following configurations are sufficient.
# Server
server.port=9090# Enabling H2 Console
spring.h2.console.enabled=true# Datasource
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=# JPA
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
After running the Library Information System, you can easily access the H2 database with this link.
Note: Whenever this project starts, scripts inside data.sql file which is under the resources directory will run. Of course, oscar goes tooooo Spring Data for this. :)
insert into book values(1, 'SCI-FI', 'Frankenstein', 'Mary Shelley', '1818');
insert into book values(2, 'Fantastic', 'Harry Potter', 'J. K. Rowling', '1997');
Running the Service and Testing with Postman
You can easily run this project to test the REST service.
If you want to add a book to Library Information System, you can use the data.json under the project root.
After running the project, you can test the REST service. For this, open Postman, enter the URL and select GET method like below.
Again, enter the link with a book name in the database.
You can add a book to the system with POST method in Postman. First, you should enter Content-Type : application/json header key-value pair. Second, in body tab, you must enter the book information that you want to save the database in JSON format.
If you want to delete a book, you should select DELETE method in Postman and add a book name that you want to delete to the end of the link.
Note: This tutorial focuses on the combination of Spring Data, in-memory H2 and REST API. There is no validation for object fields in the project.