본문 바로가기
Study/Spring

[Spring]Builder

by 나아가는 2023. 10. 6.
반응형

@Builder

객체를 생성할 때 생성자 대신에 사용할 수 있는 클래스이다.

생성 시점에 값을 채워주는 역할은 생성자와 동일하지만, 어떤 필드에 어떠한 값을 입력하는지 명확하게 알 수 있다.

@Builder
public class test(){
	String a;
	String b;
	public test(String a, String b){
			this.a = a;
			this.b = b;
	}
}
String a = a;
String b = b;

// 1. 기본생성자 사용할 경우 
new test(b, a); 

// 2. 빌더 패턴 사용할 경우
test.builder() 
	.a(a)
	.b(b)
	.build();

예제

LombokDto.java

import lombok.Builder;
import lombok.Data;

import java.util.List;

@Data
@Builder // new 대신 builder 패턴으로 객체 생성> 생성자 파라미터에 자동으로 디폴트 값 넣어줌
@Builder(toBuilder = true) // deep copy 지원
public class LombokDto {
    private final String name;
    private final int amount;
    @Builder.Default // 이것이 없으면 null로 초기화 된다. 
	      // Builder내부적으로 필드를 초기화시키기 때문에
				// @Value 에서는 안붙여도 상관없음 > delombok으로 확인 가능
    private String email = "default@email";
		@Singular("hobbyItem")
    private List<String> hobbies;
}

LombokTest.java

import com.jojoldu.book.springboot.web.dto.LombokDto;
import org.junit.Test;
import org.junit.jupiter.api.DisplayName;

public class LombokTest {

    @Test
    @DisplayName("lombok 빌더 테스트")
    public void dtoBuilderTest(){
        LombokDto dto = LombokDto.builder()
                .name("홍길동")
                .amount(5000)
//                .email("test@abc.com")
                .build();
        System.out.println("builder dto: "+ dto);
    }
// builder dto: LombokDto(name=홍길동, amount=5000, email=default@email, password=null, hobbies=null)

		@Test
    @DisplayName("lombok 빌더 toBuilder 테스트")
    public void dtoBuilderToBuilderTest(){
        LombokDto dto1 = LombokDto.builder()
                .name("홍길동")
                .amount(5000)
                .password("password")
								.hobbyItem("축구")
                .hobbyItem("야구")
                .build();
//        LombokDto dto2 = dto1;
        LombokDto dto2 = dto1.toBuilder().build();

        dto1.setPassword("password2");
        System.out.println("dto1: "+dto1);
        System.out.println("dto2: "+dto2);
    }
// dto1: LombokDto(name=홍길동, amount=5000, email=default@email, password=password2, hobbies=["축구","야구"])
// dto2: LombokDto(name=홍길동, amount=5000, email=default@email, password=password, hobbies=["축구","야구"])
}

build.gradle > implementation 은 main 폴더에 적용시키고, testImplementation은 test 폴더에 적용 시키는 라이브러리

...
dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-web'
	implementation 'org.springframework.boot:spring-boot-starter-aop'
	implementation 'org.springframework.boot:spring-boot-starter-validation'
	implementation 'com.fasterxml.jackson.core:jackson-core'
	implementation 'org.projectlombok:lombok:1.18.26'

	developmentOnly 'org.springframework.boot:spring-boot-devtools'

	annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
	annotationProcessor 'org.projectlombok:lombok:1.18.26'

	testImplementation 'org.springframework.boot:spring-boot-starter-test'
	testImplementation 'org.projectlombok:lombok:1.18.26'
	testImplementation 'junit:junit:4.13.1'
//	testImplementation 'org.junit.jupiter:junit-jupiter-api:5.6.0'

//	testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine'

	testAnnotationProcessor 'org.projectlombok:lombok:1.18.26'
}
...
반응형