카테고리 없음

Spring의 DI(의존성 주입) 방식 3가지

Tech_JINI 2025. 5. 12. 14:07

✅ 1. 세터 주입(Setter Injection)

@Component
public class ProductService {

    private ProductRepository productRepository;

    @Autowired
    public void setProductRepository(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    public String getProduct() {
        return productRepository.getProduct();
    }
}

@Autowired 

public void set*** (ProductRepository productRepository)

 

Spring은 자기가 컨테이너에 담아둔 Spring Bean 중에

개발자가 원하는 객체가 뭔지 타입으로 매칭

 

Setter에서도 매개변수로 타입을 열어주기 때문에 

타입으로 ProductRepository필요하다는 것을 보고 스프링이 Autowired를 넣어줌

 

단점: public으로 늘 열려있어서 스프링 말고도 개발자가 언제든지 접근 가능 

 

✅ 2. 필드 주입(Field Injection)

@Component
public class ProductService {

    @Autowired
    private ProductRepository productRepository;

    public String getProduct() {
        return productRepository.getProduct();
    }
}

@Autowired

private ProductRepository productRepository;

 

📌 특징

  • @Autowired를 필드 위에 직접 붙여서 스프링 컨테이너에 있는 빈을 주입받음
  • 코드가 간단하고 빠르게 사용할 수 있음

⚠️ 단점

  • 테스트 코드에서 주입이 어렵다 → Mock 객체 주입이 까다로움
  • 불변성 보장이 어렵고, DI 프레임워크에 강하게 의존

 

✅ 3. 생성자 주입(Constructor Injection)

@Component
public class ProductService {

    private final ProductRepository productRepository;

    @Autowired
    public ProductService(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    public String getProduct() {
        return productRepository.getProduct();
    }
}

@Autowired // 생성자 주입 방식

ProductService(ProductRepository productRepository)

 

📌 특징

  • 생성자 파라미터에 @Autowired를 붙여 의존성 주입
  • 단일 생성자일 경우, @Autowired 생략 가능
  • 필드가 final일 경우 객체 생성 이후 변경 불가 → 불변성 보장
  • 스프링한테 타입을 필드에서 알려주는게 아니라 생성자에서 알려줌.

✅ 장점

  • 가장 안정적이고 테스트하기 쉬움