클래스 레벨 @Builder
@Builder
public class Test {
private String one;
private Long two;
public Test(Long two){
this.two = two;
}
}

lombok builder는 기본적으로 allArgsConstructor 로 동작한다.
그래서 위 코드에서 @Builder는 one, two를 인자로 받는 생성자를 사용하지만 정의되지 않은 생성자이므로 컴파일 에러가 발생한다. 정의된 건 two를 받는 생성자 뿐이다.
public Test build() {
return new Test(this.one, this.two);
}
( 위 처럼 코드를 만들고 정의되지 않은 생성자로 에러가 발생할 것이다. )
생성자 레벨 @Builder
public class Test {
private String one;
private Long two;
@Builder
public Test(Long two){
this.two = two;
}
}
생성자 레벨 @Builder는 allArgsConstructor를 회피하고 의도대로 동작할 수 있다.
public class Test {
private String one;
private Long two;
public Test(Long two) {
this.two = two;
}
public static TestBuilder builder() {
return new TestBuilder();
}
public static class TestBuilder {
private Long two;
TestBuilder() {
}
public TestBuilder two(final Long two) {
this.two = two;
return this;
}
public Test build() {
return new Test(this.two);
}
public String toString() {
return "Test.TestBuilder(two=" + this.two + ")";
}
}
}
생성자 레벨 @Builder에서 빌드된 코드를 보면 build 메서드가 two를 인자로 받는 생성자를 사용하는 것을 볼 수 있다.
결론
추가 옵션없이 @Builder를 사용한다면 생성자 레벨에서 사용하자.
참고 자료
https://velog.io/@park2348190/Lombok-Builder%EC%9D%98-%EB%8F%99%EC%9E%91-%EC%9B%90%EB%A6%AC
Lombok @Builder의 동작 원리
보일러플레이트 메서드(getter/setter, constructor 등)를 직접 작성하지 않아도 대신 작성해주는 Lombok를 최근에 많이 활용하고 있다. 그나마 setter 메서드같은 경우는 값을 변경시키는 메서드는 그 목
velog.io
'spring' 카테고리의 다른 글
| spring lombok SuperBuilder (0) | 2023.10.08 |
|---|---|
| spring mongodb repository (0) | 2023.10.01 |
| Json 직렬/역직렬, @RequestBody, @ModelAttribute (0) | 2023.08.04 |
| Spring boot DI 주입 방식 (필드/수정자/생성자) (0) | 2023.07.22 |
| 스프링) Spring jpa 순환참조 (23-07-07) (0) | 2023.07.13 |