更新
根据反馈和John的回答,我已更新了不再使用@Tolerate
or的答案@Data
,而是通过@Getter
和创建访问器和变量,通过@Setter
创建默认构造函数via @NoArgsConstructor
,最后我们创建了构建器通过via所需的所有args构造函数@AllArgsConstructor
。
因为您想使用构建器模式,所以我想您想限制构造函数和mutators方法的可见性。为此,我们package private
通过和注释上的属性以及注释上的access
属性将可见性设置为。@NoArgsConstructor
@AllArgsConstructor
value
@Setter
重要
记住要正确重写toString
,equals
和hashCode
。有关详细信息,请参见Vlad Mihalcea的以下帖子:
package com.stackoverflow.SO34299054;
import static org.junit.Assert.*;
import java.util.Random;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import org.junit.Test;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@SuppressWarnings("javadoc")
public class Answer {
@Entity
@Builder(toBuilder = true)
@AllArgsConstructor(access = AccessLevel.PACKAGE)
@NoArgsConstructor(access = AccessLevel.PACKAGE)
@Setter(value = AccessLevel.PACKAGE)
@Getter
public static class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
}
@Test
public void testPersonBuilder() {
final Long expectedId = new Random().nextLong();
final Person fromBuilder = Person.builder()
.id(expectedId)
.build();
assertEquals(expectedId, fromBuilder.getId());
}
@Test
public void testPersonConstructor() {
final Long expectedId = new Random().nextLong();
final Person fromNoArgConstructor = new Person();
fromNoArgConstructor.setId(expectedId);
assertEquals(expectedId, fromNoArgConstructor.getId());
}
}
使用@Tolerate
和的旧版本@Data
:
使用@Tolerate
work允许添加noarg构造函数。
因为您想使用构建器模式,所以我想您想控制setter方法的可见性。
该@Data
注解使得生成的制定者public
,应用@Setter(value = AccessLevel.PROTECTED)
的领域,因此他们protected
。
记住要正确重写toString
,equals
和hashCode
。有关详细信息,请参见Vlad Mihalcea的以下帖子:
package lombok.javac.handlers.stackoverflow;
import static org.junit.Assert.*;
import java.util.Random;
import javax.persistence.GenerationType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Data;
import lombok.Setter;
import lombok.experimental.Tolerate;
import org.junit.Test;
public class So34241718 {
@Builder
@Data
public static class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Setter(value = AccessLevel.PROTECTED)
Long id;
@Tolerate
Person() {}
}
@Test
public void testPersonBuilder() {
Long expectedId = new Random().nextLong();
final Person fromBuilder = Person.builder()
.id(expectedId)
.build();
assertEquals(expectedId, fromBuilder.getId());
}
@Test
public void testPersonConstructor() {
Long expectedId = new Random().nextLong();
final Person fromNoArgConstructor = new Person();
fromNoArgConstructor .setId(expectedId);
assertEquals(expectedId, fromNoArgConstructor.getId());
}
}
@NoArgsConstructor
projectlombok.org/api/lombok/NoArgsConstructor.html