How to Build Objects with Any Number of Fields Using SpringBoot, Lombok, and @Builder
This article shows how to use Lombok's @Builder annotation in a SpringBoot project to create flexible object constructors, avoiding multiple overloaded constructors and allowing selective field assignment through a fluent builder API.
When a class has many attributes and different business scenarios require setting only a subset of those attributes, traditional constructors quickly become unwieldy because each combination would need its own overload.
Using Lombok's @Builder annotation generates a builder class that lets developers set any combination of fields in a readable, chainable way, eliminating the need for numerous constructors.
First, add Lombok to the project’s Maven dependencies:
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.0</version>
</dependency>Then define the domain class with the relevant Lombok annotations:
package com.ruoyi.demo.domain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class Student {
private String name;
private int age;
private String sex;
private String grade;
}The annotations have the following effects:
@Data : generates getters, setters, toString, equals, and hashCode.
@AllArgsConstructor : creates a constructor with all fields.
@NoArgsConstructor : creates a no‑argument constructor.
@Builder : produces a builder API that implements the Builder pattern for the class.
Object creation now becomes concise:
Student student = Student.builder()
.name("霸道的程序猿")
.age(3)
.sex("男")
.build();
Student student1 = Student.builder()
.name("霸道的程序猿")
.age(3)
.build();
System.out.println(student);
System.out.println(student1);Each call to builder() can set only the fields needed for the specific scenario, and the resulting objects are printed via the generated toString method.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
The Dominant Programmer
Resources and tutorials for programmers' advanced learning journey. Advanced tracks in Java, Python, and C#. Blog: https://blog.csdn.net/badao_liumang_qizhi
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
