#
@Builder Lombok annotation
The project Lombok is a popular Java library that is used to minimize/remove the boilerplate code.
For using Lombok, we need to add the Lombok dependency. My example is using Maven, so the dependency is the following:
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.26</version>
<scope>provided</scope>
</dependency>
Also, my example is using Spring Boot, and it is created by using Spring Initializr.
The @Builder
annotation is used when we need to implement a builder of a class with less code.
Here are some examples of using the @Builder annotation.
I will create 2 "Employee" classes and for each I will define a specific builder.
package com.example.builder.employee;
import lombok.Builder;
import lombok.ToString;
@ToString
@Builder(toBuilder = true)
public class Employee {
private String id;
private String name;
private String department;
private int age;
}
package com.example.builder.employee;
import lombok.Builder;
import lombok.ToString;
@Builder(builderMethodName = "myBuilder")
@ToString
public class Employee2 {
private String id;
private String name;
private String department;
private int age;
}
And here we can see how these builders can be used:
package com.example.builder;
import com.example.builder.employee.Employee;
import com.example.builder.employee.Employee2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BuilderApplication {
public static void main(String[] args) {
SpringApplication.run(BuilderApplication.class, args);
System.out.println("Here starts Spring application !");
Employee emp1 = Employee.builder()
.id("ID-1212")
.name("John")
.age(23)
.department("Finance")
.build();
Employee.EmployeeBuilder emp1Builder = emp1.toBuilder();
Employee emp11 = emp1Builder
.id("ID-1213")
.name("Anna")
.build();
System.out.println("emp1/name="+emp1.toString());
System.out.println("emp11/name="+emp11.toString());
Employee2 emp2 = Employee2.myBuilder()
.id("ID-1000")
.name("Dan")
.age(23)
.department("Marketing")
.build();
System.out.println("emp2/name="+emp2.toString());
System.out.println("------ END ------");
}
}
When we run the code we can see:
Here starts Spring application !
emp1/name=Employee(id=ID-1212, name=John, department=Finance, age=23)
emp11/name=Employee(id=ID-1213, name=Anna, department=Finance, age=23)
emp2/name=Employee2(id=ID-1000, name=Dan, department=Marketing, age=23)
------ END ------
Process finished with exit code 0
Info
The builder name can be renamed, using builderMethodName. This feature is useful when you want to use "builder" method for adding more functionalities to the new "builderMethodName" method.
The
@Builder
annotation can be used at the method level as well, by adding@Builder(builderMethodName = "builder")
annotation to a method.