@Builder
User.builder().name(UUID.randomUUID().toString()).build()
不使用 lombok 的方案
public class Example<T> {
private T foo;
private final String bar;
private Example(T foo, String bar) {
this.foo = foo;
this.bar = bar;
}
public static <T> ExampleBuilder<T> builder() {
return new ExampleBuilder<T>();
}
public static class ExampleBuilder<T> {
private T foo;
private String bar;
private ExampleBuilder() {}
public ExampleBuilder foo(T foo) {
this.foo = foo;
return this;
}
public ExampleBuilder bar(String bar) {
this.bar = bar;
return this;
}
@java.lang.Override
public String toString() {
return "ExampleBuilder(foo = " + foo + ", bar = " + bar + ")";
}
public Example build() {
return new Example(foo, bar);
}
}
}
使用 lombok 的方案 guava 16.0.1
@Builder
public class Example
{
private int foo;
private final String bar;
}
构造一个实例,属性不需要单独set
Example.builder().foo(1).bar(“test”).build()
@Builder
@Getter
public class HttpProxyContext
@Bean
public HttpProxyContext httpActivityProxyContext() {
return HttpProxyContext.builder()
.baseUrl(environment.getProperty("activity.template.host"))
.cdlTemplateDetailUrl("v1/cdl/template/detail")
.userQuestionAireDetailUrl("v1/right/getUserQuestionnaireSurveyByProfileNo")
.mktAppElasticLayerUrl("v1/layer/getMktAppElasticLayer")
.appLayerUrl("v1/layer/getAppLayerConfig")
.monitorUrl("v1/layer/saveMonitor")
.objectMapper(objectMapper())
.build();
}
@Builder(toBuilder = true) @Getter public class UserInfo { private String name; private String email; @MinMoney(message = "金额不能小于0.") @MaxMoney(value = 10, message = "金额不能大于10.") private Money price; }
@Builder注解赋值新对象
UserInfo userInfo = UserInfo.builder() .name("zzl") .email("bgood@sina.com") .build();
@Builder注解修改原对象的属性值
修改实体,要求实体上添加@Builder(toBuilder=true)
userInfo = userInfo.toBuilder() .name("OK") .email("zgood@sina.com") .build();