스프링 핵심 원리 - 기본편(스프링 컨테이너 생성)

홍범선·2023년 7월 3일
0

스프링

목록 보기
35/35

스프링 컨테이너 생성과정

  • ApplicationContext를 스프링 컨테이너라 한다. => 컨테이너란 객체를 담고있는 저장소이다.
  • ApplicationContext는 인터페이스이다.
  • 스프링 컨테이너는 XML을 기반으로 만들 수 있고, 애노테이션 기반의 자바 설정 클래스로 만들 수 있다.
  • 직전에 AppConfig를 사용했던 방식이 애노테이션 기반의 자바 설정 클래스로 스프링 컨테이너를 만든 것이다.


1. new AnnotationConfigApplicationContext하면서 AppConfig.class 정보를 주게 되면 스프링 컨테이너가 생성이 된다.


2. 스프링 컨테이너는 파라미터로 넘어온 설정 클래스 정보를 사용해서 스프링 빈을 등록한다.
@Bean이 붙은 것을 전부 호출하고 이름과 리턴되는 객체를 가지고 저장한다.
=> 빈 이름을 직접 부여할 수 있다.

  1. 스프링 빈 의존관계 설정한다.


설정 정보를 참고해서 의존관계를 주입한다.

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

  • ac.getBeanDefinitionNames() : 스프링에 등록된 모든 빈 이름을 조회한다.
  • ac.getBean() : 빈 이름으로 빈 객체(인스턴스)를 조회한다.

스프링 빈 조회 - 동일한 타입이 둘 이상

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 {

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

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

스프링 빈 조회 - 상속관계

부모 타입으로 조회하면, 자식 타입도 함께 조회한다.

profile
알고리즘 정리 블로그입니다.

0개의 댓글