Backend Development 14 min read

Detailed Guide to Lombok @Builder Annotation and Its Usage

This article provides a comprehensive tutorial on Lombok's @Builder annotation, covering basic usage, generated code details, @Singular collection handling, @Builder.Default defaults, toBuilder feature, and global configuration, with numerous Java code examples and explanations.

Top Architect
Top Architect
Top Architect
Detailed Guide to Lombok @Builder Annotation and Its Usage

01. Detailed Explanation of Lombok @Builder Usage

Builder implements the Builder design pattern, allowing step‑by‑step object creation while hiding construction details from the user.

02. Basic Usage

The @Builder annotation generates a builder API for the annotated class. Example:

Student.builder()
       .sno("001")
       .sname("admin")
       .sage(18)
       .sphone("110")
       .build();

@Builder can be placed on a class, constructor, or method; the most common use cases are on a class or constructor, while method usage is also supported.

03. What Does @Builder Generate Internally?

Creates a static inner class ThisClassBuilder with the same fields as the target class.

For each field (including final ones) a corresponding field is added to the builder.

Provides a no‑argument default constructor for the builder.

Generates setter‑like methods whose names match the field names and return the builder itself for chaining.

Creates a build() method that constructs the target object using the set values.

Generates a toString() method for the builder.

Adds a builder() method to the original class to obtain a builder instance.

Example class:

@Builder
public class User {
    private final Integer code = 200;
    private String username;
    private String password;
}

// Compiled version
public class User {
    private String username;
    private String password;
    User(String username, String password) {
        this.username = username;
        this.password = password;
    }
    public static User.UserBuilder builder() {
        return new User.UserBuilder();
    }
    public static class UserBuilder {
        private String username;
        private String password;
        UserBuilder() {}
        public User.UserBuilder username(String username) { this.username = username; return this; }
        public User.UserBuilder password(String password) { this.password = password; return this; }
        public User build() { return new User(this.username, this.password); }
        public String toString() { return "User.UserBuilder(username=" + this.username + ", password=" + this.password + ")"; }
    }
}

04. Combined Usage with @Singular

When a collection field is annotated with @Singular , Lombok generates special adder methods that add a single element or a whole collection, instead of a plain setter. Example:

Student.builder()
       .sno("001")
       .sname("admin")
       .sage(18)
       .sphone("110")
       .sphone("112") // adds another phone number
       .build();

To customize the adder method name, set the value attribute of @Singular :

@Builder
public class User {
    private final Integer id;
    private final String zipCode = "123456";
    private String username;
    private String password;
    @Singular(value = "testHobbies")
    private List
hobbies;
}

// Usage
User user = User.builder()
                .testHobbies("reading")
                .testHobbies("eat")
                .id(1)
                .username("admin")
                .password("admin")
                .build();

05. @Builder.Default

Fields annotated with @Builder.Default receive default values when the builder does not set them. Example:

@Builder
@ToString
public class User {
    @Builder.Default
    private final String id = UUID.randomUUID().toString();
    private String username;
    private String password;
    @Builder.Default
    private long insertTime = System.currentTimeMillis();
}

Using the builder without specifying id or insertTime will automatically populate them with the defaults.

06. toBuilder Feature

Setting toBuilder = true on @Builder creates a toBuilder() method that returns a builder pre‑populated with the current object's values, enabling easy modification while keeping the original immutable.

@Builder(toBuilder = true)
@ToString
public class User {
    private String username;
    private String password;
}

User user1 = User.builder().username("admin").password("admin").build();
User user2 = user1.toBuilder().username("admin2").build(); // user2 is a new instance

07. Global Configuration

Lombok allows global settings via properties, e.g., enabling/disabling @Builder , using Guava for immutable collections, and auto‑enabling @Singular :

# Whether to forbid @Builder usage
lombok.builder.flagUsage = [warning | error] (default: not set)
# Whether to use Guava for immutable collections
lombok.singular.useGuava = [true | false] (default: false)
# Auto‑enable @Singular
lombok.singular.auto = [true | false] (default: true)

Overall, Lombok's @Builder provides a powerful and concise way to implement the Builder pattern in Java.

design patternsJavacode generationAnnotationsLombokBuilder
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

login 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.