Lombok이 무엇인지 알아보고 Lombok을 사용하는 이유를 알아보자
Lombok은 Spring Boot를 개발하다보면 Getter, Setter 등과 같이 많은 코드를 작성해야하는데 이를 어노테이션기반으로 코드를 자동화하여 작성해주는 라이브러리이다.
만약에 프로젝트를 만들 때 Lombok을 추가하지 않았다면
build.gradle애
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
을 추가하고 update를 해주면 된다.
public class UserEntity {
private String userId;
private String userEmail;
private String userPassword;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
}
Lombok을 사용하지 않는다면 우리는 UserEntity class에서 getter와 setter 메서드를 구현하기 위해서는 위와 같이 변수 하나씩 선언을 해줘야한다
우리는 위 코드를 다음과 같이 Lombok을 이용해서 단순화 시킬 수 있다
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class TestEntity {
private String userId;
private String userEmail;
private String userPassword;
}
package com.jobpair.G.G.auth.Entity;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class TestEntity {
private String userId;
private String userEmail;
private String userPassword;
@Override
public String toString() {
return "UserEntity{" +
"userId='" + userId + '\'' +
", userEmail='" + userEmail + '\'' +
", userPassword='" + userPassword + '\'' +
'}';
}
}
ToString도 마찬가지로 Overriding을 하며 새로 지정해야하는 번거로움이 있었으나 Lombok을 사용하면 아래와 같이 @ToString 어노테이션을 붙임으로서 단순화시킬 수 있다.
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class TestEntity {
private String userId;
private String userEmail;
private String userPassword;
}
parameter없이 생성되는 기본 constructor를 생성해주는 annotation이다.
@NoArgsConstructor
public class User {
private String userId;
private String userEmail;
private String userPassword;
// public UserEntity() { } 해당 코드가 생략된다.
}
UserEntity userEntity = new UserEntity();
@NoArgsConstructor가 아무런 변수를 받지 않는 Constructor를 만들어주는 Annotation이었다면 @AllArgsConstructor은 객체가 갖고 있는 모든 변수를 받는 constructor를 만들어준다.
@AllArgsConstructor
public class User {
private String userId;
private String userEmail;
private String userPassword;
// 아래의 constructor를 @AllArgsConstructor이 대신 만들어준다.
// public User(String userId, String userEmail, String userPassword) {
// this.userId = userId;
// this.userEmail = userEmail;
// this.userPassword = userPassword;
// }
}
entity객체를 사용하며 실습을 할 때는 가장 많이 사용하게 된다.
@Data는 @Getter @Setter @RequiredArgsConstructor @ToString @EqualsAndHashCode.를 모두 포함하는 annotaion이다. 하지만 실무에서는 너무 무겁고 객체의 안정성을 지키기 때문에 @Data의 활동을 지양한다고 한다.
다수의 필드를 가지는 복잡한 클래스의 경우, 생성자 대신에 빌더를 사용하는 경우가 많다
@AllArgsConstructor와 비슷하게 객체를 생성하고 변수값을 주입해주는데 객체의 생성을 builder의 형식으로 제공해준다. @Builder도 모든 변수들에 대해서 build하기를 원하면 Class위에 붙이고 특정 변수에 대해 build하기를 원한다면 생성자를 작성하고 그 위에 annotation을 붙여준다.