Lombok 사용해보기

.·2021년 10월 10일
0
post-thumbnail

Project Lombok이란?

Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java.
Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.

세팅

  1. lombok 의존성 추가
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
  2. Settings - Build, Execution, Deployment - Compiler - Annotation Processors - check Enable annotation processing
  • 예시
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;

@ToString
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Member {
    private String name;
    private int age;
}

@Slf4j
public class MemberTest {
    @Test
    void createMember() {
        // 1. @NoArgsConstructor + @Setter
        Member m1 = new Member();
        m1.setName("name1");
        m1.setAge(10);
        
        // 2. @AllArgsConstructor
        Member m2 = new Member("name2", 20);
        
        // 3. @Builder
        Member m3 = Member.build()
            .name("name3")
            .age(30)
            .build();
        
        // 4. @ToString
        log.info("{}", m1);
    }
}

장점

반복적인 코드(메소드)를 애노테이션 기반으로 줄일 수 있다.
ex> get~(), set~(), 생성자 등..


참고

0개의 댓글