아무거나

[Lombok] Lombok 사전 본문

Java/Spring

[Lombok] Lombok 사전

전봉근 2020. 11. 27. 00:57
반응형
  • Intellij Lombok 사용 (Mac)

    • Preference -> Plugins -> Browse Repositories 에서 Lombok Plugin 추가
    • Prepference -> Build, Execution, Deployment -> Compiler -> Annotation Processors "Enable Annotation Processors" 체크
  • Lombok Annotations

    • @Getter @Setter
      • Getter / Setter Method 생성(모든 필드의 타입에 맞추어 생성)
      • Class에 적용하면 static을 제외한 모든 필드에 적용
      • AccessLevel 을 명시하지 않으면 public
        • 종류: PUBLIC, PROTECTED, PACKAGE, PRIVATE, NONE
        • 특정 필드만 적용에서 제외시킬때 NONE
      • Example Code [Lombok 적용]
          public class UserProfile {
              private int userSeq;
              private String userName;
              private String email;
        
              public int getUserSeq() {
                  return this.userSeq;
              }
        
              public String getUserName() {
                  return this.userName;
              }
        
              public String getEmail() {
                  return this.email;
              }
        
              public void setUserName(String userName) {
                  this.userName = userName;
              }
        
              public void setEmail(String email) {
                  this.email = email;
              }
        
              protected void setUserSeq(int userSeq) {
                  this.userSeq = userSeq;
              }
          }
        
        [Java 코드]
          @Getter 
          @Setter
          public class UserProfile {
              @Setter(AccessLevel.PROTECTED) private int userSeq;
              private String userName;
              private String email;
          }
        
    • @NoArgsConstructor, @RequiredArgsConstructor, @AllArgsConstructor
      • @NoArgsConstructor
        • 파라미터가 없는 생성자를 만든다.
        • 초기 값이 필요한 final 필드가 있을 경우, 컴파일 에러 -> @NoArgsConstructor(force=true) 를 사용
        • Example Code [Lombok 적용]
            @NoArgsConstructor(force=true)
            public class UserProfile {
                private final int userSeq;
                @NonNull private String userName;
                private String email;
            }
          
          [Java 코드]
            public class UserProfile {
                private final int userSeq;
          
                @NonNull 
                private String userName;
          
                private String email;
          
                public UserProfile() {
                    this.userSeq = 0;
                    this.userName = null;
                }
            }
          
      • @RequiredArgsConstructor
        • 초기화가 필요한 final 필드나 @NotNull 이 지정된 필드를 파라미터로 갖는 생성자를 만든다.
        • Example Code [Lombok 적용]
            @RequiredArgsConstructor
            public class UserProfile {
                private final int userSeq;
          
                @NonNull 
                private String userName;
          
                private String email;
            } 
          
          [Java 코드]
            public class UserProfile {
                private final int userSeq;
                @NonNull private String userName;
                private String email;
          
                @java.beans.ConstructorProperties({"userSeq", "userName"})
                public UserProfile(int userSeq, String userName) {
                    this.userSeq = userSeq;
                    this.userName = userName;
                }
            }       
          
        • StaticName Example Code (@RequiredArgsConstructor(staticName="bk")는 bk라는 이름의 static 팩토리 메서드 생성) [Lombok 적용]
            @RequiredArgsConstructor(staticName = "bk")
            public class TypeProfile<T> {
                private T type;
            }        
          
          [Java 코드]
            public class TypeProfile<T> {
                @NonNull  
                private T type;
          
                @java.beans.ConstructorProperties({"type"})
                private TypeProfile(T type) {
                    this.type = type;
                }
          
                public static <T> TypeProfile<T> bk(T type) {
                    return new TypeProfile<T>(type);
                }
            }        
          
      • @AllArgsConstructor
        • 모든 필드를 파라미터로 갖는 생성자를 만든다.
        • Example Code [Lombok 적용]
            @AllArgsConstructor
            public class UserProfile {
                private final int userSeq;
                @NonNull private String userName;
                private String email;
            }        
          
          [Java 코드]
            public class UserProfile {
                private final int userSeq;
                @NonNull private String userName;
                private String email;
          
                @java.beans.ConstructorProperties({"userSeq", "userName", "email"})
                public UserProfile(int userSeq, String userName, String email) {
                    this.userSeq = userSeq;
                    this.userName = userName;
                    this.email = email;
                }
            }        
          
    • @ToString
      • toString() 메서드 생성
      • static 필드가 아닌 모든 필드가 대상
        • ClassName(FieldName1=값1, FieldName2=값2...)
        • includeFieldNames = false 프린트 시 FieldName 제외 -> ClassName(값, 값...)
      • 원하지 않는 필드 제외
        • exclude="FieldName" or exclude={"FieldName1", "FieldName2"}
      • Example Code [Lombok 적용]
          @ToString
          public class UserProfile {
              private int userSeq;
              private String userName;
              private String email;
          }    
        
        [Java 코드]
          public class UserProfile {
              private int userSeq;
              private String userName;
              private String email;
        
              public String toString() {
                  return "UserProfile(userSeq=" + this.userSeq + ", userName=" + this.userName
                                      + ", email=" + this.email + ")";
              }
          }    
        
    • @EqualsAndHashCode
      • hashCode와 equals를 생성
      • @EqualsAndHashCode(of={"FieldName1", "FieldName2"}) 필요한 필드를 명시
      • @EqualsAndHashCode(exclude={"FieldName1", "FieldName2"}) 제외할 필드를 명시
      • Super Class가 존재하면 callSuper=true 명시
      • Example Code [Lombok 적용]
          @EqualsAndHashCode(of={"userSeq", "userName"})
          public class UserProfile {
              private int userSeq;
              private String userName;
              private String email;
          }      
        
        [Java 코드]
          public class UserProfile {
              private int userSeq;
              private String userName;
              private String email;
        
              public boolean equals(Object o) {
                  if (o == this) return true;
                  if (!(o instanceof UserProfile)) return false;
                  final UserProfile other = (UserProfile) o;
                  if (!other.canEqual((Object) this)) return false;
                  if (this.userSeq != other.userSeq) return false;
                  final Object this$userName = this.userName;
                  final Object other$userName = other.userName;
                  if (this$userName==null? other$userName != null: !this$userName.equals(other$userName)) 
                      return false;
                  return true;
              }
        
              public int hashCode() {
                  final int PRIME = 59;
                  int result = 1;
                  result = result * PRIME + this.userSeq;
                  final Object $userName = this.userName;
                  result = result * PRIME + ($userName == null ? 43 : $userName.hashCode());
                  return result;
              }
        
              protected boolean canEqual(Object other) {
                  return other instanceof UserProfile;
              }
          }      
        
    • @Data
      • @ToString, @EqualsAndHashCode, @RequiredArgsConstructor, 모든 필드 @Getter, final 이 아닌 필드에 @Setter 를 전부 한번에 생성
    • @Cleanup
      • 현재 변수의 스코프가 종료되기 전에 리소스가 clean up 되도록 보장해준다. -> close() 메소드를 알아서 호출하게 해줌
        • Example Code [Lombok 적용]
            public class CleanupExample {
              public static void main(String[] args) throws IOException {
                @Cleanup InputStream in = new FileInputStream(args[0]);
                @Cleanup OutputStream out = new FileOutputStream(args[1]);
                byte[] b = new byte[10000];
                while (true) {
                  int r = in.read(b);
                  if (r == -1) break;
                  out.write(b, 0, r);
                }
              }
            }
          
          [Java 코드]
            public class CleanupExample {
              public static void main(String[] args) throws IOException {
                InputStream in = new FileInputStream(args[0]);
                try {
                  OutputStream out = new FileOutputStream(args[1]);
                  try {
                    byte[] b = new byte[10000];
                    while (true) {
                      int r = in.read(b);
                      if (r == -1) break;
                      out.write(b, 0, r);
                    }
                  } finally {
                    if (out != null) {
                      out.close();
                    }
                  }
                } finally {
                  if (in != null) {
                    in.close();
                  }
                }
              }
            }      
          
    • @Builder, @Builder.Default, @Singular
      • @Builder
        • 빌더 패턴을 적용한 객체 생성 메서드를 만든다.
      • @Builder.Default
        • @Builder시에 기본값이 null인데 @Builder.Default를 사용하면 객체 생성시 field 기본값 설정
      • @Singular
        • @Builder가 적용된 클래스의 필드가 Collection 타입 일 때, 해당 필드의 값을 추가하는 메서드 생성
      • Example Code [빌더 호출 코드]
          // UserProfile(userSeq=0, userName=John Doe, email=user00@lombok.com, age=20, values=[One, Two])
          UserProfile.builder()
            .userSeq(0)
            .userName("bkjeon")
            .email("bkjeon@lombok.com")
            .value("one")
            .value("two")
            .build();
        
        [Lombok 적용]
          @Builder
          public class UserProfile {
              private final int userSeq;
              private String userName;
              private String email;
              @Builder.Default private int age = 20;
              @Singular private List<String> values;
          }      
        
        [Java 코드]
          public class UserProfile {
              private final int userSeq;
              private String userName;
              private String email;
              @Builder.Default private int age = 20;
              private List<String> values;
        
              @java.beans.ConstructorProperties({"userSeq", "userName", "email", "age", "values"})
              UserProfile(int userSeq, String userName, String email, int age, List<String> values) {
                  this.userSeq = userSeq;
                  this.userName = userName;
                  this.email = email;
                  this.age = age;
                  this.values = values;
              }
        
              public static UserProfileBuilder builder() {
                  return new UserProfileBuilder();
              }
        
              public static class UserProfileBuilder {
                  private int userSeq;
                  private String userName;
                  private String email;
                  private int age;
                  private ArrayList<String> values;
        
                  UserProfileBuilder() {
                  }
        
                  public UserProfileBuilder userSeq(int userSeq) {
                      this.userSeq = userSeq;
                      return this;
                  }
        
                  public UserProfileBuilder userName(String userName) {
                      this.userName = userName;
                      return this;
                  }
        
                  public UserProfileBuilder email(String email) {
                      this.email = email;
                      return this;
                  }
        
                  public UserProfileBuilder age(int age) {
                      this.age = age;
                      return this;
                  }
        
                  public UserProfileBuilder value(String value) {
                      if (this.values == null) this.values = new ArrayList<String>();
                      this.values.add(value);
                      return this;
                  }
        
                  public UserProfileBuilder values(Collection<? extends String> values) {
                      if (this.values == null) this.values = new ArrayList<String>();
                      this.values.addAll(values);
                      return this;
                  }
        
                  public UserProfileBuilder clearValues() {
                      if (this.values != null)
                          this.values.clear();
        
                      return this;
                  }
        
                  public UserProfile build() {
                      List<String> values;
                      switch (this.values == null ? 0 : this.values.size()) {
                          case 0:
                              values = java.util.Collections.emptyList();
                              break;
                          case 1:
                              values = java.util.Collections.singletonList(this.values.get(0));
                              break;
                          default:
                              values = java.util.Collections.unmodifiableList(new ArrayList<String>(this.values));
                      }
        
                      return new UserProfile(userSeq, userName, email, age, values);
                  }
        
                  public String toString() {
                      return "UserProfile.UserProfileBuilder(userSeq=" + this.userSeq + ", userName=" + this.userName + ", email=" + this.email + ", age=" + this.age + ", values=" + this.values + ")";
                  }
              }
          }      
        
    • @Log / @Slf4j ...
      • Log 객체들을 생성

 

참고: https://hyoj.github.io

반응형
Comments