Spring Boot/어노테이션

[Spring Boot] @Builer

수수한개발자 2022. 7. 6.
728x90

@Builer 란

Lombok에서 제공하는 API입니다.

 

보통 객체를 생성할 때 new를 사용해 객체를 생성하거나 기본 생성자 외에 파라미터를 넘겨주는 경우로 객체를 생성합니다.

@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PUBLIC)
public class Post {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;

    @Lob
    private String content;

    @Builder
    public Post(String title, String content) {
        this.title = title;
        this.content = content;
    }

}

위와 같이 Post 엔티티가 있을 때 

Post post = new Post();

Post post = new Post("글 제목", "글 내용" ); 이런 식으로 하게 됩니다. 지금은 인수가 별로 없어서 헷갈리지 않거나 실수도 없겠지만 받아오는 값이 10개 20개 이렇게 된다면 중간에 빼먹을 수도 있고 빼먹게 되면 컴파일 오류도 나게 됩니다. 하지만 하지만 생성자 위의 @Builder 어노테이션을 붙이게 되면 객체를 생성할 때 번거롭지 않게 할 수 있고 필요 없는 값은 넣지 않으면 됩니다.

 

사용법 

public void write(PostCreate postCreate) {
    Post post = Post.builder()
            .title(postCreate.getTitle())
            .content(postCreate.getContent())
            .build();
    postRepository.save(post);
}

위와 같이 Post.builder() 를 하고 변수명에 맞춰서

title("넣고 싶은 값")

content("넣고 싶은 값") 을 한뒤에

build(); 를 하면 됩니다.

public void write(PostCreate postCreate) {
    Post post = Post.builder()
            .title(postCreate.getTitle())
            .build();
    postRepository.save(post);
}

여기서 content 값을 안넣고 싶으면 title만 빌드 하면된다.

장점 

  • 가독성이 좋다.
  • 값 생성에 대한 유연함
  • 필요한 값만 받을 수 있다.
  • 객체의 불변성
728x90

'Spring Boot > 어노테이션' 카테고리의 다른 글

[Spring Boot] @Transactional  (0) 2022.06.27
[Spring Boot] @PostConstruct  (0) 2022.06.27

댓글