I have this pojo class, which is used as apart of REST request
@Data
@Builder
public class ListRequest {
@ApiModelProperty(
value = "Language, default=en",
allowableValues = "fr, de, sv, en",
example = "en"
)
private Language language=Language.en;
@Transient
@ApiModelProperty(hidden = true)
private String apiVersion = "v4";
}
I expect that the value of language
will be Language.en
if it is missing from the service request
However it is always null
.
It is Java 101 to initialize the variable that way, so I guess it is Lombok which made this issue.
Any idea what is the issue here?
EDIT: I use neither the constructor nor the builder in my code, its the spring boot who instantiate the objects.
CodePudding user response:
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, it will not work.
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.
import lombok.Builder;
import lombok.Data;
import lombok.Value;
@Data
@Builder
public class ListRequest {
@ApiModelProperty(
value = "Language, default=en",
allowableValues = "fr, de, sv, en",
example = "en"
)
private Language language=Language.en;
public static class ListRequestBuilder {
private Language language=Language.en;
}
@ApiModelProperty(hidden = true)
private String apiVersion = "v4";
}
CodePudding user response:
Please try below. @Builder will create the attribute with null by default
@Default
private Language language=Language.en;
CodePudding user response:
Here is how i managed to fix it, thanks to all the contributors. Apparently there is an issue when try to init default value in lombok with both constructor and builder Default value in lombok. How to init default with both constructor and builder
And unfortunately the annotation @Default
didnot fix the issue
I removed the @Builder
from the class and added @NoArgsConstructor
, and created a new constructor with the annotation @Builder
, and excluded all the field i need to init from that constructor
@Data
@NoArgsConstructor
public class ListRequest {
@ApiModelProperty(
value = "Language, default=en",
allowableValues = "fr, de, sv, en",
example = "en"
)
private Language language=Language.en;
@ApiModelProperty(hidden = true)
private String apiVersion;
@Builder
public ListRequest(String apiVersion){
this.apiVersion=apiVersion;
}
}