반응형
스프링 빈을 조회할 때,
타입으로 조회 시 같은 타입의 스프링 빈이 둘 이상이면 오류가 발생한다.
이때는 빈 이름을 지정하면 된다.
같은 타입의 스프링 빈 조회에 대한 처리 방법을 코드로 작성해보자.
※ 참고로, ac.getBeansOfType() 을 사용하면 해당 타입의 모든 빈을 조회할 수 있다
● 같은 타입의 스프링 빈 조회
같은 타입의 스프링 빈들을 조회하는 테스트 코드를 작성한다.
ApplicationContextSameBeanFindTest.java
package hello.core.beanfind;
import hello.core.AppConfig;
import hello.core.discount.DiscountPolicy;
import hello.core.member.MemberRepository;
import hello.core.member.MemoryMemberRepository;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class ApplicationContextSameBeanFindTest {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(SameBeanConfig.class);
@Test
@DisplayName("타입으로 조회시 같은 타입이 둘 이상 있으면, 중복 오류가 발생한다.")
void findBeanByTypeDuplicate() {
assertThrows(NoUniqueBeanDefinitionException.class,
() -> ac.getBean(MemberRepository.class));
}
@Test
@DisplayName("타입으로 조회시 같은 타입이 둘 이상 있으면, 빈 이름을 지정하면 된다.")
void findBeanByName() {
MemberRepository memberRepository = ac.getBean("memberRepository1",MemberRepository.class);
assertThat(memberRepository).isInstanceOf(MemberRepository.class);
}
@Test
@DisplayName("특정 타입을 모두 조회하기")
void findAllBeanByType() {
Map<String, MemberRepository> beansOfType = ac.getBeansOfType(MemberRepository.class);
for (String key : beansOfType.keySet()) {
System.out.println("key = " + key + " value = " + beansOfType.get(key));
}
System.out.println("beansOfType = " + beansOfType);
assertThat(beansOfType.size()).isEqualTo(2);
}
@Configuration
static class SameBeanConfig { // static 붙이면 지금 클래스에서만 쓰이겠다는 말
@Bean
public MemberRepository memberRepository1() {
return new MemoryMemberRepository();
}
@Bean
public MemberRepository memberRepository2() {
return new MemoryMemberRepository();
}
}
}
SameBeanConfig 클래스를 임시로 생성하여
같은 타입(MemberRepository)의 빈을 생성한다.
지정한 테스트 이름처럼
타입으로 빈을 조회 시, 같은 타입이 둘 이상 있으면
NoUniqueBeanDefinitionException 예외가 발생한다.
이를 해결하기 위해 같은 타입의 빈 조회시,
빈 이름(memberRepository1)을 통해 빈을 조회했다.
특정 타입(MemberRepsitory)의 빈을 모두 조회하고자 할 땐,
key, value를 통해 조회할 수 있다.
위 테스트의 결과는...
모두 통과와 동시에 MemberRepository 빈들을
key, value로 출력하는 것을 볼 수 있다.
반응형
'Java > Spring' 카테고리의 다른 글
[Spring] 빈 팩토리와 애플리케이션 컨텍스트 | BeanFactory VS ApplicationContext (0) | 2022.01.20 |
---|---|
[Spring] Spring bean(빈) 조회 - 상속 관계 (0) | 2022.01.20 |
[Spring] Spring bean(빈) 조회 - 기본 (0) | 2022.01.20 |
[Spring] Spring bean(빈) 조회 | 컨테이너에 등록된 모든 빈 조회 (0) | 2022.01.20 |
[Spring] 스프링 컨테이너 생성(@Configuration) | 스프링 빈 등록(@Bean) | 스프링 컨테이너 적용 | 스프링 의존성 주입(DI) (0) | 2022.01.15 |