✅ 3.1 빈을 수동으로 연결하는 2가지 방법 (@Bean 기반)
🧩 방법 1: @Bean 메서드 안에서 직접 호출
@Configuration
public class ProjectConfig {
@Bean
public Parrot parrot() {
var p = new Parrot();
p.setName("Kiki");
return p;
}
@Bean
public Person person() {
var p = new Person();
p.setParrot(parrot()); // 직접 메서드 호출로 DI
return p;
}
}
- 스프링 컨테이너가 알아서 싱글 인스턴스로 캐시함 (중복 아님)
- 간단하지만 결합도가 높고 유연성이 떨어짐
🧩 방법 2: @Bean 메서드 파라미터 사용
@Bean
public Person person(Parrot parrot) {
var p = new Person();
p.setParrot(parrot); // 자동 주입
return p;
}
- 더 깔끔하고 DI 철학에 부합
- 스프링이 자동으로 파라미터를 찾아서 넣어줌
✅ 3.2 @Autowired로 자동 주입하기
빈 등록은 끝났다. 이제 자동 연결하는 방법들을 학습한다.
🧪 1. 필드 주입 (추천 X)
@Component
public class Person {
@Autowired
private Parrot parrot;
}
- 장점: 코드 짧음
- 단점: 테스트 어려움, final 사용 불가
→ 실무에선 거의 안 씀
🧪 2. 생성자 주입 (가장 권장)
@Component
public class Person {
private final Parrot parrot;
@Autowired
public Person(Parrot parrot) {
this.parrot = parrot;
}
}
- 장점: final, 불변성 확보, 테스트 쉬움
- 스프링 4.3+ 부터는 생성자 하나일 경우 @Autowired 생략 가능
🧪 3. 세터 주입
@Component
public class Person {
private Parrot parrot;
@Autowired
public void setParrot(Parrot parrot) {
this.parrot = parrot;
}
}
- 장점: 선택적 주입 가능
- 단점: 의존성이 명확하지 않음 → 실무에서 잘 안 씀
⚠️ 3.3 순환 의존성(Circular Dependency)
- A → B → A 구조일 때 발생
- 생성자 주입 시 순환 의존성은 바로 오류 발생
- 세터 주입이나 @Lazy 조합으로 우회 가능하지만 설계 자체가 잘못됐다는 신호다
🎯 3.4 동일 타입 빈이 여러 개일 때 (Ambiguity 해결)
문제 상황
@Bean
public Parrot parrot1() { ... }
@Bean
public Parrot parrot2() { ... }
@Autowired
private Parrot parrot; // 🚨 오류 발생! 어떤 걸 넣어야 할지 모름
해결 1: @Primary
@Bean
@Primary
public Parrot parrot1() { ... }
해결 2: @Qualifier
@Autowired
@Qualifier("parrot2")
private Parrot parrot;
💣 이 장의 전투 교훈 요약

'프레임워크 > Spring' 카테고리의 다른 글
Spring Context: Defining Beans (0) | 2025.05.01 |
---|---|
Spring in the Real World (0) | 2025.05.01 |
@Controller VS @RestController (0) | 2025.03.26 |
REST API (0) | 2025.03.26 |
의존, 의존성 주입(DI) (0) | 2025.03.25 |