Spring
@Data,@Getter,@Setter 롬북(LOMBOK)의 기능
point_Man
2023. 2. 19. 21:06
롬북을 사용하면 코드를 간편하고 깔끔하게 정리할 수 있다.
사용하기 전과 후를 비교해보자.
public class Member {
private Long id;
private String name;
private final MemberRepository memberRepository;
private final DiscountPolicy discountPolicy;
@Autowired
public Member(MemberRepository memberRepository, DiscountPolicy
discountPolicy) {
this.memberRepository = memberRepository;
this.discountPolicy = discountPolicy;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
롬북을 사용하기전에는 생성자를 직접 만들어야하고 필드변수에 getter와 setter를 직접 만들어 주어야해서
코드가 지저분해보인다.
롬북 라이브러리를 사용하면 어떻게 될까?
@Getter
@Setter
public class Member {
private Long id;
private String name;
private final MemberRepository memberRepository;
private final DiscountPolicy discountPolicy;
}
@Getter @Setter 선언만으로 자동으로 getter, setter를 만들어준다.
코드가 훨씬 간결해지고 깔끔해졌다.
public static void main(String[] args) {
Member member = new Member(MemberRepository memberRepository,DiscountPolicy discountPolicy);
member.getName("name");
member.setName("name");
}
getter와 setter를 사용하려면 getName,setName으로 객체에 값을 가져오거나 할당 할 수 있다.
@Data를 사용하면 @Getter @Setter 선언도 생략이 가능하다.
@Data
public class Member {
private Long id;
private String name;
private final MemberRepository memberRepository;
private final DiscountPolicy discountPolicy;
}
그 이유는 @Data 애노테이션을 보면 알 수 있다
* @Getter
* @Setter
* @ToString
* @EqualsAndHashCode
* @RequredArgsConstructor
@Data는 위에 애노테이션을 모두 포함한다.
/**
* Generates getters for all fields, a useful toString method, and hashCode and equals implementations that check
* all non-transient fields. Will also generate setters for all non-final fields, as well as a constructor.
* <p>
* Equivalent to {@code @Getter @Setter @RequiredArgsConstructor @ToString @EqualsAndHashCode}.
* <p>
* Complete documentation is found at the project lombok features page for @Data</a>.
*
* @see Getter
* @see Setter
* @see RequiredArgsConstructor
* @see ToString
* @see EqualsAndHashCode
* @see lombok.Value
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface Data {
/**
* If you specify a static constructor name, then the generated constructor will be private, and
* instead a static factory method is created that other classes can use to create instances.
* We suggest the name: "of", like so:
*
* <pre>
* public @Data(staticConstructor = "of") class Point { final int x, y; }
* </pre>
*
* Default: No static constructor, instead the normal constructor is public.
*
* @return Name of static 'constructor' method to generate (blank = generate a normal constructor).
*/
String staticConstructor() default "";
}
하지만 도메인 객체에서는 @Data를 사용하지 않는 것을 추천한다
예상치 못한 메서드가 호출 될 수도 있다 도메인 객체에서는 @Getter, @Setter 정도만 사용하고
DTO같은 데이터를 전송하는 객체의 경우에는 @Data를 사용하여도 괜찮다.