Backend/SPRING

Lombok의 @Builder 기능을 상속받은 class에서도 사용하는 방법

GreatSaiyaman 2022. 5. 31. 18:53

Lombok의 Builder 어노테이션은 객체 생성 시에 속성값들을 연쇄적으로 호출하므로 코드의 품질을 높이는 데에 좋은 어노테이션입니다.

하지만 상속을 받은 class에서 사용하게 되면 어째서인지 부모 class의 속성값들을 참조하지 못하죠.

그런 경우 아래와 같은 처방을 해주시면 됩니다.

1. 부모 클래스에서 @AllArgsConstructor를 사용하여 모든 파라미터로 객체를 생성할 수 있게 어노테이션을 붙여줍니다.

@Getter
@AllArgsConstructor
public class Parent {
    private final String parentName;
    private final int parentAge;
}

 

2. 자식 클래스에서 아래와 같이 처리해 주시면 됩니다.

모든 필드를 받는 생성자를 작성하시고, 부모 클래스의 생성자를 호출하여(super) 처리해 주시면 원하시는 호출이 가능하십니다.

@Getter
public class Child extends Parent {
    private final String childName;
    private final int childAge;

    @Builder
    public Child(String parentName, int parentAge, String childName, int childAge) {
        super(parentName, parentAge);
        this.childName = childName;
        this.childAge = childAge;
    }
}
 

큰 도움이 된 블로그가 있어서 링크 걸어둡니다.

혹시 문제 시 말씀 주시면 삭제할게요.

https://www.baeldung.com/lombok-builder-inheritance

 

Lombok @Builder with Inheritance | Baeldung

Learn how to deal with the @Builder annotation when inheritance is involved.

www.baeldung.com

 

감사합니다.