From v1.16.16, you can specify the default value by adding the @ Builder.Default
annotation.
@Builder
public class Coupon {
@Builder.Default
private UUID id = UUID.randomUUID();
private String name;
private String description;
private ZonedDateTime expireDate;
}
By the way, Spring Boot was imported in v1.5.3, so if you are using an earlier version, you need to explicitly specify the version.
Lombok's @Builder is an annotation that automatically generates a builder class for a specified class.
@Value
@Builder
public class Coupon {
private UUID id;
private String name;
private String description;
private ZonedDateTime expireDate;
}
Coupon coupon = Coupon.builder()
.name("Surprised coupon")
.description("Surprised coupon")
.expireDate(ZonedDateTime.parse("2017-01-30T23:59:59+09:00", DateTimeFormatter.ISO_OFFSET_DATE_TIME))
.build();
However, the property for which no value is specified in the builder call will be null
.
Even if you try to set a default value other than null and write it in the target class as follows, it will not work.
@Value
@Builder
public class Coupon {
private UUID id = UUID.randomUUID(); //Does not apply
private String name = ""; //Does not apply
private String description;
private ZonedDateTime expireDate;
}
Therefore, this time, I will introduce how to set the default value correctly.
@ Builder
To set the default value, describe the builder class with the naming convention of target class name + Builder
as shown below. The rest is nicely complemented by Lombok.
@Value
@Builder
public class Coupon {
private UUID id;
private String name;
private String description;
private ZonedDateTime expireDate;
public static class CouponBuilder {
private UUID id = UUID.randomUUID();
private String name = "";
}
}
Recommended Posts