@Bean 여러 개 등록하기
같은 타입의 객체도 여러 개의 Bean으로 등록할 수 있다.
예를 들어 PersonRepository의 버전을 두 개 관리한다고 가정해보자.
@Bean
public PersonRepository personRepository() {
return new PersonRepository(1);
}
@Bean
public PersonRepository personRepositoryV2() {
return new PersonRepository(2);
}
PersonRepository는 생성자를 통해 버전을 전달받는다.
@RequiredArgsConstructor
public class PersonRepository {
private final int version;
public int count() {
System.out.println("version = " + version);
return 3;
}
}
이렇게 하면 Spring에는 아래와 같이 동일한 타입의 Bean이 2개 등록된다.
| Bean 이름 | 객체 |
| personRepository | PersonRepository(version = 1) |
| personRepositoryV2 | PersonRepository(version = 2) |
문제가 발생하는 이유
만약 Service에서 다음과 같이 주입받으면
@Service
public class PersonService {
private final PersonRepository personRepository;
}
Spring은 어떤 PersonRepository를 주입해야 하는지 알 수 없다.
왜냐하면 PersonRepository 타입의 Bean이 두 개이기 때문이다.
@Qualifier로 Bean 선택하기
이럴 때 @Qualifier를 사용하면 원하는 Bean을 지정할 수 있다.
public PersonService(
@Qualifier("personRepository")
PersonRepository personRepository
) {
this.personRepository = personRepository;
}
Bean 이름으로 지정하면 된다.
@Bean
public PersonRepository personRepository() {
return new PersonRepository(1);
}
그러면 version = 1인 객체가 주입된다.
반대로
public PersonService(
@Qualifier("personRepositoryV2")
PersonRepository personRepository
) {
this.personRepository = personRepository;
}
처럼 작성하면 version = 2인 객체가 주입된다.
@Order
같은 타입의 Bean이 여러 개일 때 우선순위를 지정할 수 있다.
@Bean
@Order(1)
public PersonRepository personRepository() {
...
}
@Bean
@Order(2)
public PersonRepository personFileRepository() {
...
}
숫자가 작을수록 우선순위가 높다.
'BackEnd > Spring' 카테고리의 다른 글
| [Spring] JPA 메서드 명명 규칙(Query Method) (0) | 2026.08.07 |
|---|---|
| [Spring] Proxy란? @Transactional과 @Lazy가 동작하는 원리 (0) | 2026.08.06 |
| Spring Boot에서 HTML 페이지 출력하기 (Thymeleaf 사용법) (0) | 2026.08.06 |
| [Spring] Lazy Loading vs Eager Loading (0) | 2026.08.05 |
| [Spring] JPA CascadeType과 Flush (0) | 2026.08.05 |
댓글