Blog

[SpringCore] 스프링 컨테이너와 스프링 빈 - 스프링 컨테이너에 등록된 빈 조회 테스트

Category
Author
citeFred
citeFred
Tags
PinOnMain
1 more property
ApplicationContext 의 구현체 AnnotationConfigApplicationContext를 통한 스프링 컨테이너 빈 조회
Table of Content

@Bean으로 등록된 스프링 빈

AppConfig.java를 @Configuration 어노테이션을 통해 스프링 설정 정보로 사용하고 있다.
@Configuration public class AppConfig { @Bean public MemberService memberService() { return new MemberServiceImpl(memberRepository()); } @Bean public MemberRepository memberRepository() { return new MemoryMemberRepository(); } @Bean public OrderService orderService() { return new OrderServiceImpl(memberRepository(), discountPolicy()); } @Bean public DiscountPolicy discountPolicy() { return new RateDiscountPolicy(); } }
Java
복사
다음처럼 4개의 개발자가 지정한 클래스가 빈으로 등록되어 있으며 해당 AppConfig.java또한 하나의 빈으로 인식되어 로드된 것을 확인했었다.

테스트 코드를 통해 스프링 빈 기본 조회

package hello.core.beanfind; import hello.core.AppConfig; import hello.core.member.MemberService; import hello.core.member.MemberServiceImpl; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import static org.assertj.core.api.Assertions.*; import static org.junit.jupiter.api.Assertions.*; public class ApplicationContextBasicFindTest { AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class); @Test @DisplayName("빈 이름으로 조회") void findBeanName() { //when MemberService memberService = ac.getBean("memberService", MemberService.class); //then assertThat(memberService).isInstanceOf(MemberService.class); } @Test @DisplayName("이름 없이 타입으로만 조회") void findBeanByType() { //when MemberService memberService = ac.getBean(MemberService.class); //then assertThat(memberService).isInstanceOf(MemberServiceImpl.class); } @Test @DisplayName("구체 타입으로 조회") void findBeanByName2() { //when MemberService memberService = ac.getBean("memberService", MemberServiceImpl.class); //then assertThat(memberService).isInstanceOf(MemberServiceImpl.class); } //-----------여기까지 성공 테스트 @Test @DisplayName("빈 이름으로 조회 실패") void findBeanByNameFail() { assertThrows(NoSuchBeanDefinitionException.class, () -> ac.getBean("xxxxx", MemberService.class)); } }
Java
복사
AnnotationConfigApplicationContext 클래스 객체를 통해서 스프링 컨테이너에 등록된 빈을 확인 할 수 있다. 기본적으로 getBean(빈이름, 타입) 메서드를 통해서 조회 할 수 있다.

테스트용 @Configuration으로 테스트 - 1 중복과 명시

동일한 타입이 둘 이상인 경우 중복 오류

package hello.core.beanfind; import hello.core.discount.DiscountPolicy; import hello.core.member.MemberRepository; import hello.core.member.MemoryMemberRepository; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; public class ApplicationContextSameBeanFindTest { AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(SameBeanConfig.class); @Test @DisplayName("타입으로 조회 시 같은 타입이 둘 이상 있으면, 중복 오류가 발생한다.") void findBeanByTypeDuplicate() { MemberRepository bean = ac.getBean(MemberRepository.class); } @Configuration static class SameBeanConfig { @Bean public MemberRepository memberRepository1() { return new MemoryMemberRepository(); } @Bean public MemberRepository memberRepository2() { return new MemoryMemberRepository(); } } }
Java
복사
MemberRepository 빈을 찾으려 하지만 @Bean 어노테이션으로 빈 등록이 지정된 것이 Memory1, Memory2로 구현체가 2개일 수 있다.
NoUniqueBeanDefinitionException: No qualifying bean of type 'hello.core.member.MemberRepository' available: expected single matching bean but found 2:
@Test @DisplayName("타입으로 조회 시 같은 타입이 둘 이상 있으면, 중복 오류가 발생한다.") void findBeanByTypeDuplicate() { //MemberRepository bean = ac.getBean(MemberRepository.class); // NoUniqueBeanDefinitionException 이 발생 assertThrows(NoUniqueBeanDefinitionException.class, () -> ac.getBean(MemberRepository.class)); }
Java
복사

동일한 타입이 둘 이상인 경우 이름을 명시하여 찾기

위 처럼 동일한 타입의 빈이 두개 이상인 경우 getBean(이름, 타입) 으로 이름을 명시하여 찾을 수 있다.
package hello.core.beanfind; import hello.core.member.MemberRepository; import hello.core.member.MemoryMemberRepository; 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.AssertionsForClassTypes.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; public class ApplicationContextSameBeanFindTest { //given AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(SameBeanConfig.class); ... @Test @DisplayName("타입으로 조회시 같은 타입이 둘 이상 있으면, 빈 이름을 지정하면 된다.") void findBeanByName() { //when MemberRepository memberRepository = ac.getBean("memberRepository1", MemberRepository.class); //then assertThat(memberRepository).isInstanceOf(MemberRepository.class); } ... @Configuration static class SameBeanConfig { @Bean public MemberRepository memberRepository1() { return new MemoryMemberRepository(); } @Bean public MemberRepository memberRepository2() { return new MemoryMemberRepository(); } } }
Java
복사

특정 타입 모두 조회하기

getBeansOfType()을 통해서는 파라미터로 전달하는 타입의 빈들을 map 컬렉션으로 받아 올 수 있다. key 값에는 이름, value 값에는 주소값을 확인 할 수 있다.
package hello.core.beanfind; import hello.core.member.MemberRepository; import hello.core.member.MemoryMemberRepository; 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.AssertionsForClassTypes.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; public class ApplicationContextSameBeanFindTest { //given AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(SameBeanConfig.class); ... @Test @DisplayName("특정 타입을 모두 조회하기") void findAllBeanByType() { //when 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); //then assertThat(beansOfType.size()).isEqualTo(2); } @Configuration static class SameBeanConfig { @Bean public MemberRepository memberRepository1() { return new MemoryMemberRepository(); } @Bean public MemberRepository memberRepository2() { return new MemoryMemberRepository(); } } }
Java
복사

테스트용 @Configuration으로 테스트 - 2 상속관련

기본 원칙은 빈 조회 시 부모 타입으로 조회하면 자식 타입도 함께 조회한다.
따라서 자바 객체 최상위 부모인 Object 클래스를 조회하면 모든 스프링 빈을 조회 할 수 있다.

부모 타입으로 조회 시 자식이 둘 이상 있으면 중복 오류가 발생한다.

DIscountPolicy가 2개의 구현체가 빈으로 등록 되었다고 가정하자.(고정 할인fixDiscount.. , 비율 할인 rateDiscount..)
package hello.core.beanfind; import hello.core.discount.DiscountPolicy; import hello.core.discount.FixDiscountPolicy; import hello.core.discount.RateDiscountPolicy; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; public class ApplicationContextExtendsFindTest { AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(TestConfig.class); @Test @DisplayName("부모 타입으로 조회 시, 자식이 둘 이상 있으면 오류가 발생한다.") void findBeanByParentTypeDuplicate() { DiscountPolicy bean = ac.getBean(DiscountPolicy.class); } @Configuration static class TestConfig { @Bean public DiscountPolicy rateDiscountPolicy() { return new RateDiscountPolicy(); } @Bean public DiscountPolicy fixDiscountPolicy() { return new FixDiscountPolicy(); } } }
Java
복사
getBean()을 통해서 DiscountPolicy(부모 클래스)의 빈을 조회하면 구현체(자식)가 2개이므로 NoUniqueBeanDefinitionException 중복 예외가 발생하게 된다.
해당 예외가 발생하는 것을 검증하는 테스트 코드
@Test @DisplayName("부모 타입으로 조회 시, 자식이 둘 이상 있으면 오류가 발생한다.") void findBeanByParentTypeDuplicate() { //DiscountPolicy bean = ac.getBean(DiscountPolicy.class); assertThrows(NoUniqueBeanDefinitionException.class, () -> ac.getBean(DiscountPolicy.class)); }
Java
복사
이 상황에서도 빈 이름을 명시하면 조회 할 수 있다.
package hello.core.beanfind; import hello.core.discount.DiscountPolicy; import hello.core.discount.FixDiscountPolicy; import hello.core.discount.RateDiscountPolicy; 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 static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; public class ApplicationContextExtendsFindTest { //given AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(TestConfig.class); ... @Test @DisplayName("부모 타입으로 조회 시, 자식이 둘 이상 있으면, 빈 이름을 지정하면 된다.") void findBeanByParentTypeBeanName() { //when DiscountPolicy rateDiscountPolicy = ac.getBean("rateDiscountPolicy", DiscountPolicy.class); //then assertThat(rateDiscountPolicy).isInstanceOf(RateDiscountPolicy.class); } ... @Configuration static class TestConfig { @Bean public DiscountPolicy rateDiscountPolicy() { return new RateDiscountPolicy(); } @Bean public DiscountPolicy fixDiscountPolicy() { return new FixDiscountPolicy(); } } }
Java
복사

하위 타입을 명시하여 조회 할 수 있다.

package hello.core.beanfind; import hello.core.discount.DiscountPolicy; import hello.core.discount.FixDiscountPolicy; import hello.core.discount.RateDiscountPolicy; 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.AssertionsForClassTypes.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; public class ApplicationContextExtendsFindTest { //given AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(TestConfig.class); ... @Test @DisplayName("특정 하위(자식) 타입으로 조회") void findBeanBySubType() { //when RateDiscountPolicy bean = ac.getBean(RateDiscountPolicy.class); //then assertThat(bean).isInstanceOf(RateDiscountPolicy.class); } ... @Configuration static class TestConfig { @Bean public DiscountPolicy rateDiscountPolicy() { return new RateDiscountPolicy(); } @Bean public DiscountPolicy fixDiscountPolicy() { return new FixDiscountPolicy(); } } }
Java
복사

부모 타입으로 조회 시 자식이 모두 조회된다.

상속 관계에 따라 상위 클래스를 조회하면 등록된 자식 클래스의 빈 들이 모두 조회 된다.
package hello.core.beanfind; import hello.core.discount.DiscountPolicy; import hello.core.discount.FixDiscountPolicy; import hello.core.discount.RateDiscountPolicy; 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.AssertionsForClassTypes.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; public class ApplicationContextExtendsFindTest { //given AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(TestConfig.class); ... @Test @DisplayName("부모 타입으로 모두 조회하기") void findAllBeansByParentType() { //when Map<String, DiscountPolicy> beansOfType = ac.getBeansOfType(DiscountPolicy.class); //then assertThat(beansOfType.size()).isEqualTo(2); for (String key : beansOfType.keySet()) { System.out.println("key = " + key + " value = " + beansOfType.get(key)); } } @Configuration static class TestConfig { @Bean public DiscountPolicy rateDiscountPolicy() { return new RateDiscountPolicy(); } @Bean public DiscountPolicy fixDiscountPolicy() { return new FixDiscountPolicy(); } } }
Java
복사
최상위 클래스인 Object로 조회하면 스프링 프레임워크에 등록된 빈들도 모두 조회 할 수도 있다.
... @Test @DisplayName("최상위 타입으로 모두 조회하기") void findAllBeansByObjectType() { //when Map<String, Object> beansOfType = ac.getBeansOfType(Object.class); //print for (String key : beansOfType.keySet()) { System.out.println("key = " + key + " value = " + beansOfType.get(key)); } } ...
Java
복사
Search
 | Main Page | Category |  Tags | About Me | Contact | Portfolio