개발/Java

Lombok 이란?

728x90

공식문서 : "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."

 

  • 어노테이션 기반으로 코드를 자동완성 해주는 라이브러리
  • 장점
    • 코드 자동생성을 통한 생상성 향상
    • 반복되는 코드를 줄여 가독성 및 유지보수성 향상
    • 빌더패턴이나 로그 자동 생성 등 다양한 방면으로 활용 가능
  • 단점
    • 프로젝트에 참여하는 모든 팀원이 Lombok을 써야함.
  •  종류
    • 생성자 관련 
      • @AllArgsConstructor 
        • 모든 변수를 사용하는 생성자를 자동완성 시켜주는 어노테이션
      • @NoArgsConstructor
        • 어떠한 변수도 사용하지 않는 기본 생성자를 자동완성 시켜주는 어노테이션
      • @RequiredArgsConstructor
        • 특정 변수만 사용하여 자동완성 시켜주는 어노테이션
        • @Nonnull을 통해 해당 변수를 생성자의 인자로 추가할 수 있음.
        • 혹은 final로 선언해도 의존성을 주입받을 수 있다.
    • @EqualsAndHashCode
      • 클래스에 대한 equals 함수와 hashCode함수를 자동으로 생성해준다.
      • 만약 서로 다른 두 객체에서 특정 변수의 이름이 똑같은 경우 같은 객체로 판단을 하고 싶을 때 사용 (동등성 보장)
    • @Data
      • 공식문서 : All together now: A shortcut for @ToString@EqualsAndHashCode@Getter on all fields, and @Setter on all non-final fields, and @RequiredArgsConstructor!
      • @ToString, @EaualsAndHashCode, @Getter, @Setter, @RequiredArgsConstructor를 자동완성 시켜준다.
    • @Builder
      • 공식문서 : ... and Bob's your uncle: No-hassle fancy-pants APIs for object creation!
      • 해당 클래스의 객체 생성에 Builder패턴을 적용시켜준다. 
      • 모든 변수들에 대해 build 하기를 원하면 @Builder를 붙이면 되지만
      • 특정 변수만을 build하기를 원한다면 생성자를 작성하고 그 위에 @Builder를 붙여주면 된다.
      • *빌더 패턴 :
        • 싱글턴, 팩터리 패턴등과 같이 생성 패턴중 하나임.
        • 복잡한 객체를 생성하는 방법을 정의하는 클래스와 표현하는 방법을 정의하는 클래스를 별도로 분리하여, 서로 다른 표현이라도 이를 생성할 수 있는 동일한 절차를 제공하는 패턴.
        • 이펙티브 자바 설명
          • 객체 생성을 깔끔하고 유연하게 하는 기법 
          • 생성자가 인기가 많을 때 Builder 패턴 적용을 고려하라
          • 생성자에 매개변수가 많다면 빌더를 고려하라
        • 단점 : 
          • 다른 생성자를 호출하는 생성자가 많아서, 인자가 추가되면 코드 수정이 어려움
          • 코드 가독성이 떨어짐
            • 특히 인자수가 많아지면 코드가 길어지고 읽기 어려워짐.
        • *자바빈 패턴
          • 빌더패턴의 대안
          • setter 메소드를 통해 가독성을 향상시킴
          • 장점
            • 각 인자의 의미를 파악하기 쉬워짐
            • 복잡하게 여러 개의 생성자 만들지 않아도 됨
          • 단점
            • 객체의 일관성이 깨짐(1회의 호출로 객체 생성이 안끝남)
            • setter가 있으므로 immutable한 클래스 생성 불가.
// 빌더 패턴
Member customer = Member.build()
    .name("홍길동")
    .age(30)
    .build();
    
// 자바빈 패턴
NutritionFacts cocaCola = new NutritionFacts();
cocaCola.setServingSize(240);
cocaCola.setServings(8);
cocaCola.setCalories(100);
cocaCola.setSodium(35);
cocaCola.setCarbohdydrate(27);

 

    • @Delegate
      • 한 객체의 메소드를 다른 객체로 위임시켜줌.
      • 특정 인터페이스 정보를 이용하여 위임할 클래스에 있응 메소드들을 위임받을 클래스들에게 위임키시게 된다.
public class DelegationExample {
    @Delegate(types=List.class)
    private final List<string> names = new ArrayList<string>();
}


// 위는 아래 코드와 일치함

public class DelegationExample {
    private final List<string> names = new ArrayList<string>();
 
    public boolean add(final String item) {
        return this.names.add(item);
    }
 
    public boolean remove(final String item) {
        return this.names.remove(item);
    }
 
    //...그 외의 List의 메쏘드들
}

 

 

  •  
    • @Log
      • Captain's Log, stardate 24435.7: "What was that line again?"
      • @Log4j2를 이용하면 해당 클래스의 로그 클래스를 자동으로 완성시켜준다.
    • 그 외 기타
      • @Cleanup
        • Automatic resource management: Call your close() methods safely with no hassle.
        • IO 처리나 JDBC 코딩을 할 때 try-catch-finally 문의 finally 절을 통해서 close() 메소드를 해줘야 하는게 여간 번거로운 일이 아니었다.
        • 위 어노테이션을 통해 해당 자원이 자동으로 닫히는 것을 보장한다
      • @ToString
        • No need to start a debugger to see your fields: Just let lombok generate a toString for you!
        • Class에 있는 필드들을 검사해서 문자열로 변환해주는 toString() 메소드를 생성함.
      • @Value
        • Immutable classes made very easy.
        • Immutable Class를 생성해줌.
        • @Data와 비슷하지만 모든 필드를 기본적으로 private , final로 설정하고, setter 함수 생성을 생략
      • @Synchonized
        • synchronized done right: Don't expose your locks.
        • 파라미터로 넘긴 Object 단위로 락을 걸거나, 파라미터로 아무것도 입력하지 않으면 어노테이션이 사용된 메소드 단위로 락을 건다.
      • @SneakyThrows
        • To boldly throw checked exceptions where no one has thrown them before!
        • 메소드 선언부에 사용되는 throws 키워드 대신 사용하는 어노테이션으로 예외 클래스를 파라미터로 입력 받는다.
        • checked exceptions을 처리해준다.
      • @With
        • Immutable 'setters' - methods that create a clone but with one changed field.
          • value : 필드의 접근 제어자를 지정함
          • onMethod : 메서드의 어노테이션을 추가한다.
          • onParam : 파라미터에 어노테이션을 추가한다.
      • val
        • Finally! Hassle-free final local variables 
        • Local 변수 선언을 val을 이용하면 초기화 값을 이용하여 변수 타입을 유추하여 final로 생성해줌
        • (JS에서 var키워드와 동일)
      • @Getter(lazy=true)
        • Laziness is a virtue!
        • You can let lombok generate a getter which will calculate a value once, the first time this getter is called, and cache it from then on. This can be useful if calculating the value takes a lot of CPU, or the value takes a lot of memory. To use this feature, create a private final variable, initialize it with the expression that's expensive to run, and annotate your field with @Getter(lazy=true). The field will be hidden from the rest of your code, and the expression will be evaluated no more than once, when the getter is first called. There are no magic marker values (i.e. even if the result of your expensive calculation is null, the result is cached) and your expensive calculation need not be thread-safe, as lombok takes care of locking.
        • 동기화를 이용하여 최초 1회만 호출
        • 많은 CPU 사용량혹은 메모리를 점유하는 연산에서 유용하다

 

import lombok.Getter;

public class GetterLazyExample {
  @Getter(lazy=true) private final double[] cached = expensive();
  
  private double[] expensive() {
    double[] result = new double[1000000];
    for (int i = 0; i < result.length; i++) {
      result[i] = Math.asin(i);
    }
    return result;
  }
}

 

다음 포스트에서 Lombok의 동작원리까지 살펴보자.

 

 

참고

mangkyu.tistory.com/78#:~:text=Lombok%EC%9D%B4%EB%9E%80%20%EC%96%B4%EB%85%B8%ED%85%8C%EC%9D%B4%EC%85%98%20%EA%B8%B0%EB%B0%98%EC%9C%BC%EB%A1%9C,%EC%9E%90%EB%8F%99%EC%99%84%EC%84%B1%20%EC%8B%9C%ED%82%AC%20%EC%88%98%20%EC%9E%88%EB%8B%A4.

projectlombok.org/

johngrib.github.io/wiki/builder-pattern/

 

'개발 > Java' 카테고리의 다른 글

Lombok의 동작원리  (1) 2021.05.13
java.util.collections 총정리 set편  (0) 2021.05.13
mixin이란  (0) 2021.05.11
hashCode()  (0) 2021.05.08
자바 스레드 덤프 Thread Dump 분석  (1) 2021.04.26