[SpringBoot] @어노테이션 3

Oksun Noh·2024년 12월 23일
0

Spring & Spring Boot

목록 보기
3/6

@NoArgsConstructor

  1. 인자가 없는 기본 생성자를 생성
@NoArgsConstructor
public class Product {
    private String name;
    private double price;
}
// @noArgsContructor로 인해 생략된 생성자
public Product() { // 빈 생성자 }

@AllArgsConstructor

  1. 모든 필드를 인자로 받는 생성자를 생성
  2. 객체를 생성할 때 모든 필드를 한 번에 초기화 하고싶을때 주로 사용
// 모든 필드를 인자로 받는 생성자를 생성하고 싶을 때

@AllArgsConstructor
public class Order {
    private String orderId;
    private String product;
    private int quantity;
}

/* @AllArgsConstructor 어노테이션을 사용하여 모든 필드를 인자로 받는 생성자가 자동으로 생성
아래 Order 생성자를 생략할 수 있음*/

public Order(String orderId, String product, int quantity) {
    this.orderId = orderId;
    this.product = product;
    this.quantity = quantity;
}

@RequiredArgsConstructor

  1. final 필드@NonNull이 붙은 필드만 인자로 받는 생성자를 생성
  2. 객체의 불변성을 유지하고자 할 때 주로 사용
  3. 쉽게 생각하면 객체 초기화를 스프링이 '알아서' 해준다고 보면 될 것 같음
@RequiredArgsConstructor
public class User {
    private final String username; // final 필드
    private final String email;     // final 필드
    private int age;                // 일반 필드
/* @RequiredArgsConstructor 어노테이션으로 인해
아래 생성자 생략 가능 */
public User(String username, String email) {
    this.username = username;
    this.email = email;

profile
저는 만두를 좋아합니다

0개의 댓글