본문 바로가기
Spring/1. 스프링 핵심 원리 기본편

[Spring] #10. 스프링 빈 조회

by 2nyong 2023. 4. 25.

1. 컨테이너에 등록된 모든 빈 조회

  • AppConfig는 @Configuration 어노테이션이 적용된 스프링 빈 설정 파일을 의미한다. (이름 짓기에 따라 다를 수 있음)
class ApplicationContextInfoTest {

    AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);

    @Test
    @DisplayName("모든 빈 출력하기")
    void findAllBean() {
        String[] beanDefinitionNames = ac.getBeanDefinitionNames();
        for (String beanDefinitionName : beanDefinitionNames) {
            Object bean = ac.getBean(beanDefinitionName);
            System.out.println("name(key) = " + beanDefinitionName + " object(value) = " + bean);
        }
    }
}

2. 개발자가 등록한 모든 빈 조회

  • 스프링이 내부적으로 사용하기 위해 등록한 빈을 제외한다.
class ApplicationContextInfoTest {

    AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);

    @Test
    @DisplayName("애플리케이션 빈 출력하기")
    void findApplicationBean() {
        String[] beanDefinitionNames = ac.getBeanDefinitionNames();
        for (String beanDefinitionName : beanDefinitionNames) {
            BeanDefinition beanDefinition = ac.getBeanDefinition(beanDefinitionName);

            // Role ROLE_APPLICATION: 개발자가 등록한 애플리케이션 빈
            // Role ROLE_INFRASTRUCTURE: 스프링이 내부적으로 사용하는 빈
            if (beanDefinition.getRole() == BeanDefinition.ROLE_APPLICATION) {
                Object bean = ac.getBean(beanDefinitionName);
                System.out.println("name(key) = " + beanDefinitionName + " object(value) = " + bean);
            }
        }
    }
}

3. 특정 스프링 빈 조회 - 빈 이름

import static org.assertj.core.api.Assertions.*;

class ApplicationContextBasicFindTest {

    AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);

    @Test
    @DisplayName("빈 이름으로 조회")
    void findBeanByName() {
        MemberService memberService = ac.getBean("memberService", MemberService.class);
        assertThat(memberService).isInstanceOf(MemberServiceImpl.class);
    }
}

4. 특정 스프링 빈 조회 - 빈 타입

  • 빈의 이름과 타입으로 조회하는 방법보다 간결하지만, 동일한 타입의 빈이 존재할 경우 중복 에러가 발생한다.
  • 중복 에러가 발생할 경우에는 빈 이름과 함께 조회한다.
import static org.assertj.core.api.Assertions.*;

class ApplicationContextBasicFindTest {

    AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);

    @Test
    @DisplayName("빈 타입으로 조회")
    void findBeanByType() {
        MemberService memberService = ac.getBean(MemberService.class);
        // MemberService memberService = ac.getBean(MemberServiceImpl.class); // 구현체로도 조회 가능
        assertThat(memberService).isInstanceOf(MemberServiceImpl.class);
    }
}

5. 특정 스프링 빈 조회 - 동일한 빈 타입 모두

import static org.assertj.core.api.Assertions.*;

class ApplicationContextBasicFindTest {

    AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(SameBeanConfig.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 {
        @Bean
        public MemberRepository memberRepository1() {
            return new MemoryMemberRepository();
        }

        @Bean
        public MemberRepository memberRepository2() {
            return new MemoryMemberRepository();
        }
    }
}

6. 스프링 빈 조회 - 상속 관계

  • 부모 타입으로 조회하면 자식 타입도 함께 조회한다.
  • 따라서 Object 타입으로 조회하면, 모든 스프링 빈을 조회한다.
  • 이럴 경우, 이름을 사용한 조회나 모두 조회를 활용해 빈을 조회한다.
import static org.junit.jupiter.api.Assertions.assertThrows;

public class ApplicationContextExtendsFindTest {

    AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(TestConfig.class);

    @Test
    @DisplayName("부모 타입으로 조회시, 자식이 둘 이상 있으면 중복 오류 발생")
    void findBeanByParentTypeDuplicate() {
        assertThrows(NoUniqueBeanDefinitionException.class, () -> ac.getBean(DiscountPolicy.class));
    }

    @Configuration
    static class TestConfig {
        @Bean
        public DiscountPolicy rateDiscountPolicy() {
            return new RateDiscountPolicy();
        }

        @Bean
        public DiscountPolicy fixDiscountPolicy() {
            return new FixDiscountPolicy();
        }
    }
}

 

댓글