동일 타입의 여러 Bean이 있을 때 스프링이 어떻게 DI를 처리하느냐

Primary · Qualifier · Collection · Resource · Inject

스크린샷 2025-09-07 오후 3.41.15.png

@Component
**@Primary**
public class Pikachu implements Pokemon { ... }    // bean name: "pikachu"

@Component
public class Squirtle implements Pokemon { ... }   // bean name: "squirtle"

@Component
public class Charamander implements Pokemon { ... } // bean name: "charamander"

1. @Autowired

1) @Primary — 다중 Bean 중 기본 우선순위 지정

@Service("pokemonServicePrimary")
public class PokemonService {
    private final Pokemon pokemon;
    @Autowired
    public PokemonService(Pokemon pokemon) {
        this.pokemon = pokemon;   // 타입 기준 매칭 → 후보 3개 → @Primary 승!
    }
}

언제 쓰나?

동일 타입 빈이 여러 개일 때 “기본값”을 정해두고, 특별히 지정 안 하면 그 빈을 쓰게 하고 싶을 때


2) @Qualifier — 특정 Bean 명시적으로 선택

@Service("pokemonServiceQualifier")
public class PokemonService {
    @Autowired
    public PokemonService(**@Qualifier**("squirtle") Pokemon pokemon) {
        this.pokemon = pokemon;  // 이름으로 정확히 지목
    }
}

언제 쓰나?

여러 구현체 중 특정 빈을 확실히 선택해야 할 때 (환경/시나리오별 전략 교체 등)