Java/Spring framework

Spring framework core (2) - ApplicationContext

감동이중요해 2020. 1. 5. 23:53

IoC Container - ApplicationContext

역할

  1. Bean instance 생성
  2. 의존 관계 설정
  3. Bean 제공

Bean 등록 방법

  1. XML

    • <bean> 으로 등록
    • 모든 bean을 수동으로 등록해야 하기 때문에 번거로움
    • 구현체 : ClassPathXmlApplicationContext
  2. Java

    • @Configuration annotation을 붙인 class 사용
    • @Bean으로 직접 선언
    • 구현체 : AnnotationConfigApplicationContext
  3. Component-scan

    • Spring 2.5부터 지원
    • @Component, @Service, @Control 등 Bean 등록에 사용되는 Annotation을 scan하여 자동으로 등록

@Autowired

  • IoC container에서 Bean을 찾는다.

  • required option으로 필수 여부를 가릴 수 있다.

    • default는 true이기 때문에 bean을 찾지 못하면 application이 구동되지 않는다.
      @Autowired(required=false) ExampleBean exampleBean;
      @Autowired(required=true) ExamppleBean zexampplebean;
  • 같은 타입의 Bean이 여러개라면?

    • @Primary
    • @Qualifier (Bean ID)
    • 같은 타입의 Bean 모두 주입하기

@Autowired 동작원리

  • Bean 라이프사이클에서 이미 Bean이 생성되었다고 정의하고 같은 타입의 Bean을 불러온다.

  • BeanPostProcessor

    • Bean의 라이프사이클 중 bean 초기화 전후 동작을 정의하는 Interface
    • postProcessBeforeInitialization (Bean 등록 전)
      • AutowiredAnnotationBeanPostProcessor에서@Autowired 처리
    • postProcessAfterInitialization (Bean 등록 후)

@Component와 ComponentScan

  • @ComponentScan의 기본값은 현재 class부터 scan을 시작한다.

    • @SpringBootApplication@ComponentScan을 참조하고 있으므로 Spring boot는 main class부터 scan을 시작한다.
  • @ComponentScan은 Filter를 가지고 있다.

    • @SpringBootApplicationTypeExcludeFilter, AutoConfigurationExcludeFilter 를 기본 Filter로 가지고 있다.