Usage of @builder annotation in lombok

In Lombok, the @Builder annotation is used to simplify the use of the builder pattern. After using the @Builder annotation, Lombok will automatically generate a builder class for creating objects with multiple properties.

When using the @Builder annotation, you need to pay attention to the following points:

Add the @Builder annotation on the class to be annotated with @Builder.
You need to use the @Builder.Default annotation to specify the default value of the property.
The builder class will automatically generate a no-argument construction method through which the object is created.
The generated builder class will contain property setter methods, which can be called in a chain.
Here is an example using the @Builder annotation:

import lombok.Builder;
import lombok.Getter;

@Getter
@Builder
public class Person {
    
    
    private String name;
    private int age;
    @Builder.Default
    private String gender = "unknown";
}

// 使用示例
Person person = Person.builder()
        .name("John")
        .age(25)
        .build();

In the above example, the @Builder.Default annotation is used to set the default value of the gender attribute to "unknown". We can then use the generated builder class Person.builder() to create a Person object and set the property values ​​through a chain of calls. Finally, the final object is created using the build() method.

Using the @Builder annotation can simplify the process of creating objects with multiple properties, avoiding the tedious code of manually writing builders.

Guess you like

Origin blog.csdn.net/weixin_50503886/article/details/132487832