본문 바로가기
Web Programming

Java - Lombok활용법, 쉽게 Builder class 만들기

by 맑은안개 2022. 10. 14.

Overview

Lombok 을 사용하여 쉽게 Builder class를 생성해본다.

Environment

Windows 10

Visual Studio Code

Java 11


📄 build.gradle

dependencies {
    // Use JUnit Jupiter for testing.
    testImplementation 'org.junit.jupiter:junit-jupiter:5.7.2'
    compileOnly 'org.projectlombok:lombok:1.18.24'
    annotationProcessor 'org.projectlombok:lombok:1.18.24'
}

📄 FlatFileSplitter

Builder패턴을 적용하기 위해 @Builder 어노테이션을 class에 지정한다.

package lombok.builderexam;

import java.nio.file.Path;

import lombok.Builder;

@Builder
public class FlatFileSplitter {

    private final Path originResource;
    private final Path targetResource;
    private final int splitLineCount;

    public void exec() throws Exception {

        // Valid parameteres

        System.out.println(
                String.format(
                        "originResource path %s \n" +
                                "targetResource path %s \n" +
                                "splitLineCount %d",
                        originResource.toAbsolutePath(),
                        targetResource.toAbsolutePath(),
                        splitLineCount));
    }

}

📄 테스트코드 작성

package lombok.builderexam;

import java.nio.file.Path;

import org.junit.jupiter.api.Test;

public class TestFlatFileSplitter {

    @Test
    public void TestFlatFileSplitter() throws Exception {

        FlatFileSplitter flatFileSplitter = FlatFileSplitter.builder()
                .originResource(Path.of("/origin/origin.csv"))
                .targetResource(Path.of("/target/target.csv"))
                .splitLineCount(10000)
                .build();

        flatFileSplitter.exec();
    }

}

Output

originResource path D:\origin\origin.csv 
targetResource path D:\target\target.csv 
splitLineCount 10000

📄 Default value

@Default 어노테이션을 지정하여 Default value를 설정한다.

@Builder
public class FlatFileSplitter {

    private final Path originResource;
    private final Path targetResource;
    @Default
    private final int splitLineCount = 1000;

테스트 코드에서 다음과 같이 splitLineCount를 삭제하고 테스트를 실행한다.

        FlatFileSplitter flatFileSplitter = FlatFileSplitter.builder()
                .originResource(Path.of("/origin/origin.csv"))
                .targetResource(Path.of("/target/target.csv"))
                .build();

Output

originResource path D:\origin\origin.csv 
targetResource path D:\target\target.csv 
splitLineCount 1000
반응형