Skip to main content

Command Palette

Search for a command to run...

Project Lombok in Java: Eliminate Boilerplate Code Like a Pro

Updated
5 min read
Project Lombok in Java: Eliminate Boilerplate Code Like a Pro
N
Java & Spring Boot learner | Writing beginner-friendly technical articles | Exploring backend development

In Java development, developers often write a lot of boilerplate code such as:

  • Getters

  • Setters

  • Constructors

  • toString()

  • equals() and hashCode()

Although these methods are important, writing them repeatedly makes the code verbose, repetitive, and harder to maintain.

This is where Project Lombok comes in.

Project Lombok is a Java library that helps developers reduce boilerplate code using annotations. Instead of manually writing repetitive code, Lombok generates it automatically during compilation.

With Lombok, developers can focus more on business logic rather than writing repetitive code.

What is Project Lombok?

Project Lombok is a Java library that processes annotations and generates code at compile time. It automatically generates:

  • Getter methods

  • Setter methods

  • Constructors

  • toString()

  • equals() and hashCode()

  • Builder pattern implementation and much more.

Lombok injects the generated code into the .class file during compilation, which means the Java source file remains clean while the compiled class contains the full implementation.

Why Use Lombok?

Without Lombok:

public class User{

  private String name;
  private int age;

  public String getName(){
     return name;
  }

  public void setName(String name){
      this.name = name;
   }

   public int getAge(){
      return age;
    }

   public void setAge(int age){
      this.age = age;
    }
}

With Lombok:

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class User{

    public String name;
    private int age;
}

See the difference?

The code becomes cleaner, shorter, and easier to maintain.

Adding Lombok to a Maven Project

Add the dependency in pom.xml.

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

Important Note (IDE Compilation Error)

Sometimes developers see red errors in IntelliJ or Eclipse, even though the program runs successfully.

This happens because:

  • Lombok generates code during compilation

  • The IDE cannot see the generated code

Solution:

  1. Install the Lombok plugin

  2. Enable Annotation Processing

Once this is done, the IDE simulates the generated code and the errors disappear.

10 Frequently Used Lombok Features

Let's explore the most useful Lombok annotations every Java developer should know.

1. val and var

Lombok provides val and var to infer the variable type automatically.

import lombok.val;
import lombok.var;

public class Example{

    public static void main(String[] args){

       val message = "Hello Lombok";
       var number = 10;
    }
}

Key Points:

  • val -> Immutable( final variable )

  • var -> Mutable variable

  • Works only for local variables

  • Initialization is required

2. @NonNull

  • @NonNull automatically generates a null check.

If a null value is passed, Lombok throws a NullPointerException.

Example:

import lombok.NonNull;

public class UserService{

    public void registerUser(@NonNUll String username){
          
        System.out.println(username);
     }
}

Generated logic:

if(username == null){
    
   throw new NullPointerException("username is marked non-null but is null");

}

This helps avoid manual null checking.

3. @Getter and @Setter

Lombok can automatically generate getter and setter methods.

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class Student{

   private String name;
   private int marks;
}

Default Behavior

  • Generated methods are public

You can also control access level:

@Setter(AccessLevel.PRIVATE)

Class Level Usage

@Getter
@Setter
public class Student{

     private String name;
     private int marks;
}
  • @Getter applies to all non-static fields

  • @Setter applies to all non-final fields

4. @ToString

This annotation automatically generates the toString() method.

import lombok.ToString;

@ToString
public class Product{

   private String name;
   private double price;
}

Output:

Product(name=Phone, price=25000)

Excluding Fields

@ToString(exclude = "price")

5. Constructors in Lombok

Lombok can generate constructors automatically.

No Argument Constructor

@NoArgsConstructor

All Argument Constructor

@AllArgsConstructor

Required Arguments Constructor

@RequiredArgsConstructor

This generates a constructor for:

  • final fields

  • fields annotated with @NonNull

6. @EqualsAndHashCode

This annotation generates:

  • equals()

  • hashCode()

@EqualsAndHashCode
public class Employee{

      private String id;
      private String name;
}

By default, Lombok uses all non-static and non-transient fields to generate these methods.

7. @Data

@Data is one of the most popular Lombok annotations.

It is shortcut for:

  • @Getter

  • @Setter

  • @ToString

  • @EqualsAndHashCode

  • @RequiredArgsConstructor

Example:

import lombok.Data;

@Data
public class User{

    private String name;
    private int age;
}

This single annotation generates all essential methods.

8. @Value (Immutable Objects)

@Value is the immutable version of @Data

Features:

  • All fields become private and final

  • No setters

  • Class becomes final

  • Getter methods generated

  • Constructor generated

  • equals(), hashCode(), toString() generated.

Example:

import lombok.Value;

@Value
public class Address{

   String city;
   String country;
}

9. @Builder

@Builder implements the Builder Design pattern.

Example:

import lombok.Builder;

@Builder
public class Order{

   private String product;
   private int quantity;
}

Usage:

Order order = Order.builder()
                   .product("Laptop")
                   .qunatity(2)
                   .build();

Benefits:

  • Clean object creation

  • Avoids constructor overload

  • Improves readability

10. @Cleanup

@Cleanup automatically closes resources when execution exists the scope.

Example:

import lombok.Cleanup;
import java.io.*;

public class FileExample{

    public void readFile() throws Exception {

    @Cleanup BufferedReader reader = new BufferedReader(new FileReader("test.txt"));

System.out.println(reader.readLine());
}
}

This ensures resources are automatically cleaned up.

Advantages of Lombok

  • Reduces boilerplate code

  • Improves readability

  • Faster development

  • Cleaner codebase

  • Less chance of human error

Disadvantages of Lombok

  • Requires IDE plugin

  • Hidden generated code

  • Can confuse beginners

  • Sometimes causes debugging difficulty

When Should You Use Lombok?

Lombok is widely used in:

  • Spring Boot projects

  • Microservices

  • Enterprise applications

  • Backend APIs

It is especially useful when working with:

  • DTO classes

  • Entity classes

  • Model classes

Conclusion

Project Lombok is a powerful Java library that significantly reduces boilerplate code using annotations.

By automatically generating common methods like getters, setters, constructors, equals, hashCode, and builder patterns, Lombok helps developers focus on writing clean and maintainable business logic.

If you're working on modern Java applications or Spring Boot projects, mastering Lombok is definitely a valuable skill for interviews and real-world development.

More from this blog

CoreJava

19 posts

I have written and published a comprehensive blog series titled "CoreJava" on Hashnode, based on my learning journey from basics to advanced. The series includes topics like OOP, Collections, Exception Handling, Multithreading, and Java Streams, explained with clear examples and practical insights to help learners build a strong foundation in java.