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
반응형
'Web Programming' 카테고리의 다른 글
Java - 문제 해결: UnrecognizedPropertyException: Unrecognized field (0) | 2022.11.24 |
---|---|
Java Map객체를 Pojo(Model) class로 변환 ( JsonSetter, ObjectMapper 사용법 ) (0) | 2022.11.24 |
gRPC - From Java(Spring) Client to Python Server 예제 (0) | 2022.09.02 |
문제해결: No ParameterResolver registered for parameter (0) | 2022.06.07 |
카프카(kafka) - VSCode에서 Java Producer/Consumer 생성 with Gradle (0) | 2021.12.31 |