Back to feed
ASH avatar
ASH

2026. 5. 5.·base·

Spring 타입 기반 주입의 동작

Spring DI

spring

스프링의 타입 기반 주입은 Nest처럼 토큰과 provider가 매핑되어 있어 토큰이라는 key로 provider 인스턴스를 찾는 느낌이 아니라, 컨테이너에 있는 빈들 중에서 특정 타입 자리에 들어갈 수 있는 빈을 찾는 동작이다.

즉 주입 요청 타입을 기준으로 호환되는 빈 후보를 검색한다고 이해할 수 있다.

kotlin
interface PaymentService {
    fun pay()
}

@Service
class KakaoPaymentService : PaymentService {
    override fun pay() {}
}
kotlin
@Service
class OrderService(
    private val paymentService: PaymentService
)

이때 OrderService 인스턴스를 만드려면 생성자 파라미터 paymentService에 무언가를 넣어줘야하는데 스프링은 이때 이런식의 동작과정을 거친다.

  1. 이 생성자에서 필요한건 PaymentService 타입이다
  2. 컨테이너 안의 빈들을 본다
  3. 그중 PaymentService 타입에 들어갈 수 있는 빈을 찾는다.
  4. KaKaoPaymentService는 PaymentService를 구현하니까 가능
  5. 해당 빈을 주입한다.

그래서 이와 같은 이유로 같은 타입 bean이 여러개면 에러가 발생한다.

kotlin
interface PaymentService {
	fun pay()
}

@Service
class KaKaoPaymentService : PaymentService {
	override fun pay() {}
}

@Service
class NaverPaymentService: PaymentService {
	override fun pay() {}
}
kotlin
class OrderService(
    private val paymentService: PaymentService
)

이 상황에서 만약 Nest처럼 타입명이 식별자가 되어 bean이 타입하나에 매핑되는 구조였다면 에러가 발생하지 않았겠지만
스프링에선

  • KakaoPaymentService도 PaymentService 자리에 들어갈 수 있음
  • NaverPaymentService도 PaymentService 자리에 들어갈 수 있음

타입 기준으로 후보가 여러개가 되어버려 어떤 bean을 주입할지가 모호해져 에러가 발생하게 된다.

0
Comments

Join the thread

Leave feedback, ask for clarification, or keep a focused discussion attached to this article.

0 comments
No comments yet. Start the first thread for this article.
Current user avatar
Styling with Markdown is supported