Java를 이용해 코드를 작성하다 보면 Getter, Setter 처럼 단순하게 반복해서 작성해야 하는 코드가 상당히 많은데 이런 코드를 Annotation을 이용해 대신 작성해줘 코드 길이를 줄여주는 라이브러리이다.
@Getter
@Setter
public class Memo {
private Long id;
private String username;
private String contents;
}
본래라면 Getter, Setter를 작성하는 것으로도 멤버변수의 개수당 코드 2줄씩 추가되지만 Lombok을 사용함으로써 @Getter , @Setter annotation을 활용해 코드의 길이를 줄일 수 있다.
@Getter, @Setter
위에서 활용한 어노테이션으로 클래스 이름 위에 적용하면 모든 변수들에 대해 적용되고, 변수 이름 위에 적용하면 해당 변수들만 적용할 수 있다.
@AllArgsConstructor
해당 어노테이션을 활용하면 아래 코드처럼 모든 변수를 매개변수를 통해 생성하는 생성자를 자동완성 시켜준다.
@AllArgsConstructor
public class Memo {
private Long id;
private String username;
private String contents;
public Memo(Long id, String username, String contents) {
this.id = id;
this.username = username;
this.contents = contents;
}
}
@NoArgsConstructor
해당 어노테이션은 아래와 같이 어떠한 변수도 사용하지 않는 기본 생성자를 만들어주는 어노테이션이다.
public class Memo {
private Long id;
private String username;
private String contents;
public Memo(){
}
}
@RequiredArgsConstructor
해당 어노테이션은 @NonNull 어노테이션이나 final로 선언된 변수만을 사용해 생성자를 만들어주는 어노테이션이다.
public class Memo {
private final Long id;
private final String username;
@NonNull
private String contents;
public Memo(Long id, String username, String contents) {
this.id = id;
this.username = username;
this.contents = contents;
}
}