How to Set Default Values in Lombok’s @Builder – A Complete Guide

This tutorial explains how to provide default values for fields when using Lombok's @Builder pattern in Java, covering Maven setup, plain POJO definition, Lombok annotations, Builder.Default, custom builder class names, the toBuilder feature, and the trade‑offs of each approach.

Programmer DD
Programmer DD
Programmer DD
How to Set Default Values in Lombok’s @Builder – A Complete Guide

1. Overview

In this tutorial we explore how to provide default values for fields when using Lombok's Builder pattern.

2. Maven Dependency

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

3. POJO without Lombok

public class Pojo {
    private String name;
    private boolean original;
}

To make this class usable we need getters, possibly a no‑args constructor for ORM, and a builder class.

4. Adding Lombok Annotations

@Getter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Pojo {
    private String name;
    private boolean original;
}

The @Builder annotation alone does not assign default values, so the following tests fail.

5. Builder.Default Annotation

@Builder
public class Pojo {
    @Builder.Default
    private String name = "foo";
    @Builder.Default
    private boolean original = true;
}

This annotation supplies defaults but does not work with a generated no‑args constructor.

6. Custom Builder Class Name

@Builder(builderClassName = "PojoBuilder")
public class Pojo {
    private String name = "foo";
    private boolean original = true;
}

Specifying the builder class name avoids rename issues during refactoring.

7. Using toBuilder

@Builder(toBuilder = true)
public class Pojo {
    private String name = "foo";
    private boolean original = true;
}

Enabling toBuilder creates a builder from an existing instance, eliminating double initialization.

8. Summary

We have demonstrated several ways to give Lombok's @Builder default values, each with its own trade‑offs. Choose the approach that best fits your project.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaannotationsLombokBuilderDefault Values
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.