What is lombok and how to use it?

Feeling bored of asking your IDE to generate getters and setters for your Java POJO classes?

And also implementing toString(), equals() and hashCode() methods ?

Lombok comes to the rescue.

It automatically generates all of them for you.

All you have to do is install lombok and then add the required annotations.

How to install lombok?

Step 1:

Add the below dependency in your maven project :

	<dependency>
		<groupId>org.projectlombok</groupId>
		<artifactId>lombok</artifactId>
		<version>1.18.12</version>
		<scope>provided</scope>
	</dependency>

If you are using Spring Boot you can ignore the version.

If you are using a plain Java project , you can download lombok jar from their website (https://projectlombok.org/download) and add it to your build path.

Step 2:

Run maven clean install so that the dependency is downloaded to your local maven repository

Step 3:

Go to your maven repository (path will be something like C:/users/username/.m2/) and double click on the jar downloaded . This will find out IDE installations in your machine and install lombok in them.

This will allow IDE’s to recognize lombok and give you code completion suggestions. Also it won’t complain of compilation error when you add lombok annotations.

Step 4:

Start using lombok!

Add @Data annotation on top of your class to generate all of the below:

  • Getters
  • Setters
  • equals() method
  • hashCode() method
  • toString() method
import lombok.Data;
@Data
public class Team {
	private Integer id;
	private String name;
	private Integer size;
}

If you want to generate just getters use @Getter annotation instead of @Data

If you want to generate just setters use @Setter annotation

If you want to generate just equals and hashcode methods , use @EqualsAndHashCode annotation.

Once you add the annotation , you can access the getters and setters in other classes like you had added on your own .

For example the name of the above ‘Team’ class can be accessed as team.getName() .

That’s it.

Lombok makes your code look cleaner.

Shortcomings:

There are few shortcomings though :

  1. It fiddles with Code Coverage generator tool like JaCoCo (https://www.eclemma.org/jacoco/) . To ignore lombok generated code while calculating code coverage follow this ( How to ignore code coverage for lombok generated code ? )
  2. It fiddles with Code Quality scans like Fortify . This can be solved by delomboking the code and only scanning the result code. This feature is provided by lombok itself. The instructions can be seen here (https://projectlombok.org/features/delombok)


Posted

in

by

Comments

One response to “What is lombok and how to use it?”

  1. […] hashCode() and toString() methods. Of course IDE’s can auto generate them and tools like lombok can generate them for you with the help of […]

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading