티스토리 뷰

카테고리 없음

lombok @Builder2 사용방법

JONG HYEOK2 2023. 11. 30. 20:07

https://lanuni.tistory.com/entry/lombok-Builder

 

lombok @Builder

이 게시글은 공부했던 내용을 기억하기 위한 포스팅입니다. 이 게시글은 공부했던 내용을 기록하기 위한 용도로, 옳지 않은 부분이 있을 수 있습니다. 틀린 부분이나 더 좋은 의견은 댓글로 공

lanuni.tistory.com

 

1. Builder를 통한 객체 생성 예시

        Test test = Test.builder()
                        .id(1L)
                        .address("seoul")
                        .name("jh2")
                        .build();

 

@Builder는 클래스, 생성자 또는 메서드 배치할 수 있다.

 

만약 다음과 같은 Test 클래스가 있을 때

public class Test {
    private Long id;
    private String name;
    private String address;
    private LocalDateTime createdAt;
    private boolean trueYn;
}

 

@Builder 어노테이션은 클래스 혹은 생성자가 일반적으로 사용된다.

 

2. 생성자 Builder 어노테이션

Test.java

public class Test {
    private Long id;
    private String name;
    private String address;
    private LocalDateTime createdAt;
    private boolean trueYn;

    @Builder
    public Test(Long id, String name, String address) {
        this.id = id;
        this.name = name;
        this.address = address;
        this.createdAt = LocalDateTime.now();
        this.trueYn = true;
    }
}

 

 

 

Test.class

public class Test {
    private Long id;
    private String name;
    private String address;
    private LocalDateTime createdAt;
    private boolean trueYn;

    public Test(Long id, String name, String address) {
        this.id = id;
        this.name = name;
        this.address = address;
        this.createdAt = LocalDateTime.now();
        this.trueYn = true;
    }

    public static TestBuilder builder() {
        return new TestBuilder();
    }

    public static class TestBuilder {
        private Long id;
        private String name;
        private String address;

        TestBuilder() {
        }

        public TestBuilder id(final Long id) {
            this.id = id;
            return this;
        }

        public TestBuilder name(final String name) {
            this.name = name;
            return this;
        }

        public TestBuilder address(final String address) {
            this.address = address;
            return this;
        }

        public Test build() {
            return new Test(this.id, this.name, this.address);
        }

        public String toString() {
            return "Test.TestBuilder(id=" + this.id + ", name=" + this.name + ", address=" + this.address + ")";
        }
    }
}

 - 생성자 @Builder 부여한 경우 정책에 따라 원하는 값만 받을 수 있도록 가능하다.

예를 들어, createdAt의 경우 따로 값을 입력받지 않고, 객체 생성시간을 기준으로 세팅되도록 하였으며, trueYn 변수는 default값으로 true를 반환하도록 하였다.

 

- 자동으로 생성된 toString의 경우에도, 생성자에 있었던 변수들을 기준으로 생성된 것을 확인할 수 있다.

 

3. 클래스 @Builder 어노테이션

Test.java

@Builder
public class Test {
    private Long id;
    private String name;
    private String address;
    private LocalDateTime createdAt;
    private boolean trueYn;
}

 

Test.class

public class Test {
    private Long id;
    private String name;
    private String address;
    private LocalDateTime createdAt;
    private boolean trueYn;

    Test(final Long id, final String name, final String address, final LocalDateTime createdAt, final boolean trueYn) {
        this.id = id;
        this.name = name;
        this.address = address;
        this.createdAt = createdAt;
        this.trueYn = trueYn;
    }

    public static TestBuilder builder() {
        return new TestBuilder();
    }

    public static class TestBuilder {
        private Long id;
        private String name;
        private String address;
        private LocalDateTime createdAt;
        private boolean trueYn;

        TestBuilder() {
        }

        public TestBuilder id(final Long id) {
            this.id = id;
            return this;
        }

        public TestBuilder name(final String name) {
            this.name = name;
            return this;
        }

        public TestBuilder address(final String address) {
            this.address = address;
            return this;
        }

        public TestBuilder createdAt(final LocalDateTime createdAt) {
            this.createdAt = createdAt;
            return this;
        }

        public TestBuilder trueYn(final boolean trueYn) {
            this.trueYn = trueYn;
            return this;
        }

        public Test build() {
            return new Test(this.id, this.name, this.address, this.createdAt, this.trueYn);
        }

        public String toString() {
            return "Test.TestBuilder(id=" + this.id + ", name=" + this.name + ", address=" + this.address + ", createdAt=" + this.createdAt + ", trueYn=" + this.trueYn + ")";
        }
    }
}

- static class인 TestBuilder가 자동으로 생성된다. 

- Test에 선언된 모든 파라미터를 받을 수 있는 메서드가 제공된다.

- 주의해야 할 점은 toString도 자동으로 생성되는 것을 확인할 수 있다.

 JPA에서 양방향으로 매핑할 경우 toString을 잘못사용하면 무한에 빠질 수 있다고 들었다. 괜찮을지 궁금하다.

 

The configurable aspects of builder are:

  • The builder's class name (default: return type + 'Builder')
  • The build() method's name (default: "build")
  • The builder() method's name (default: "builder")
  • If you want toBuilder() (default: no)
  • The access level of all generated elements (default: public).
  • (discouraged) If you want your builder's 'set' methods to have a prefix, i.e. Person.builder().setName("Jane").build() instead of Person.builder().name("Jane").build() and what it should be.

Example usage where all options are changed from their defaults:
@Builder(builderClassName = "HelloWorldBuilder", buildMethodName = "execute", builderMethodName = "helloWorld", toBuilder = true, access = AccessLevel.PRIVATE, setterPrefix = "set")

 

 

Builder 클래스 이름, set methods의 prefix 등을 변경할 수 있는 옵션도 있다. 

 

만약 궁금하다면, docs 참고.

https://projectlombok.org/features/Builder

 

@Builder

 

projectlombok.org

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함