스프링 컨테이너 생성
- 스프링 컨테이너 : ApplicationContext
- AnnotationConfigApplicationContext는 ApplicationContext의 구현체
스프링 컨테이너 생성 과정
1. 스프링 컨테이너 생성

2. 스프링 빈 등록

- 빈 이름을 설정하지 않으면 함수 이름이 빈 이름으로 자동 등록된다.
- 빈 이름을 직접 부여할 수도 있다. @Bean(name="name")
- 빈 이름은 항상 서로 다른 이름을 부여해야 한다.
3. 스프링 빈 의존관계 설정

- 스프링에서는 빈을 생성하고, 의존관계를 주입하는 단계가 나누어져 있다.
- 자바 코드로 스프링 빈을 등록하면, 빈 생성과 의존관계 주입이 한번에 처리된다.
컨테이너에 등록된 모든 빈 조회
코드
public class ApplicationContextInfoTest {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);
@Test
@DisplayName("모든 빈 출력하기.")
void findBean(){
String[] beanDefinitionNames = ac.getBeanDefinitionNames();
for (String beanDefinitionName : beanDefinitionNames) {
Object bean = ac.getBean(beanDefinitionName);
System.out.println("name = " + beanDefinitionName + ", bean = " + bean);
}
}
}
결과
name = org.springframework.context.annotation.internalConfigurationAnnotationProcessor, bean = org.springframework.context.annotation.ConfigurationClassPostProcessor@2d36e77e
name = org.springframework.context.annotation.internalAutowiredAnnotationProcessor, bean = org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor@61c9c3fd
name = org.springframework.context.annotation.internalCommonAnnotationProcessor, bean = org.springframework.context.annotation.CommonAnnotationBeanPostProcessor@3b0c9195
name = org.springframework.context.event.internalEventListenerProcessor, bean = org.springframework.context.event.EventListenerMethodProcessor@366c4480
name = org.springframework.context.event.internalEventListenerFactory, bean = org.springframework.context.event.DefaultEventListenerFactory@2c7b5824
name = appConfig, bean = hello.core.AppConfig$$EnhancerBySpringCGLIB$$e7bee251@302a07d
name = memberService, bean = hello.core.member.MemberServiceImpl@5cdd09b1
name = orderService, bean = hello.core.order.OrderServiceImpl@8c11eee
name = memberRepository, bean = hello.core.member.MemoryMemberRepository@7e8dcdaa
name = discountPolicy, bean = hello.core.discount.RateDiscountPolicy@681a8b4e
- 실제 등록하지 않은 기본 bean까지 모두 출력된다.
수정된 코드
@Test
@DisplayName("어플리케이션 빈 출력하기.")
void findApplicationBean(){
String[] beanDefinitionNames = ac.getBeanDefinitionNames();
for (String beanDefinitionName : beanDefinitionNames) {
BeanDefinition beanDefinition = ac.getBeanDefinition(beanDefinitionName);
if(beanDefinition.getRole() == BeanDefinition.ROLE_APPLICATION){
Object bean = ac.getBean(beanDefinitionName);
System.out.println("name = " + beanDefinitionName + ", bean = " + bean);
}
}
}
- BeanDefinition.ROLE_APPLICATION : 직접 등록한 어플리케이션 빈
- BeanDefinition.ROLE_INFRASTRUCTURE : 스프링이 내부에서 사용하는 빈
스프링 빈 조회 - 기본
- ac.getBean(빈이름, 타입)
- ac.getBean(타입)
public class ApplicationContextBasicFindTest {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);
@Test
@DisplayName("빈 이름으로 조회")
void findBeanByName() {
MemberService memberService = ac.getBean("memberService", MemberService.class);
assertThat(memberService).isInstanceOf(MemberServiceImpl.class);
}
@Test
@DisplayName("타입으로만 조회")
void findBeanByType() {
MemberService memberService = ac.getBean(MemberService.class);
assertThat(memberService).isInstanceOf(MemberServiceImpl.class);
}
@Test
@DisplayName("구체 타입으로 조회")
void findBeanByName2() {
MemberService memberService = ac.getBean("memberService", MemberServiceImpl.class);
assertThat(memberService).isInstanceOf(MemberServiceImpl.class);
}
@Test
@DisplayName("빈 이름으로 조회X")
void findBeanByNameX() {
assertThrows(NoSuchBeanDefinitionException.class,
() -> ac.getBean("xxxx", MemberService.class));
}
}
스프링 빈 조회 - 동일 타입이 둘 이상
public class ApplicationContextSameBeanFindTest {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(SameBeanConfig.class);
@Configuration
static class SameBeanConfig {
@Bean
public MemberRepository memberRepository1() {
return new MemoryMemberRepository();
}
@Bean
public MemberRepository memberRepository2() {
return new MemoryMemberRepository();
}
}
@Test
@DisplayName("타입으로 조회 시 같은 타입이 둘 이상이면, 중복 오류 발생")
void findBeanByTypeDuplication() {
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));
}
assertThat(beansOfType.size()).isEqualTo(2);
}
}
스프링 빈 조회 - 상속관계
- 부모 타입으로 조회하면, 자식 타입도 모두 함께 조회된다.
- 따라서, Object 타입으로 조회하면, 모든 스프링 빈을 조회
- 부모 타입으로 조회 시, 자식이 둘 이상 있으면, 중복 오류가 발생한다.
- 중복을 피하기 위해서는, 빈 이름을 지정
- 또는 특정 하위 타입으로 조회
BeanFactory와 ApplicationContext

BeanFactory
- 스프링 컨테이너의 최상위 인터페이스다.
- 스프링 빈을 관리하고 조회하는 역할을 담당한다.
- getBean() 을 제공한다.
- 지금까지 우리가 사용했던 대부분의 기능은 BeanFactory가 제공하는 기능이다.
ApplicationContext
- BeanFactory 기능을 모두 상속받아서 제공한다.
- 빈을 관리하고 검색하는 기능을 BeanFactory가 제공해주는데, 그러면 둘의 차이가 뭘까?
- 애플리케이션을 개발할 때는 빈을 관리하고 조회하는 기능은 물론이고, 수 많은 부가기능이 필요하다.
ApplicationContext의 부가 기능

- 메세지소스 : 국제화 기능 제공
- 환경변수 : 로컬, 개발, 운영 등을 구분해서 처리
- 어플리케이션 이벤트 : 어플리케이션 내의 이벤트 발행, 구독을 편리하게 지원
- 리소스 조회 : 외부 URL이나 파일 등에서 리소스를 편리하게 조회
스프링 빈 설정 메타 정보 - BeanDefinition
- 스프링이 다양한 설정 형식을 지원할 수 있는 이유 → BeanDefinition
- XML이든 자바코드이든 각 정보를 기반으로 BeanDefinition을 생성

BeanDefinition 정보
- BeanClassName: 생성할 빈의 클래스 명(자바 설정 처럼 팩토리 역할의 빈을 사용하면 없음)
- factoryBeanName: 팩토리 역할의 빈을 사용할 경우 이름, 예) appConfig
- factoryMethodName: 빈을 생성할 팩토리 메서드 지정, 예) memberService
- Scope: 싱글톤(기본값)
- lazyInit: 스프링 컨테이너를 생성할 때 빈을 생성하는 것이 아니라, 실제 빈을 사용할 때 까지 최대한 생성을 지연처리 하는지 여부
- InitMethodName: 빈을 생성하고, 의존관계를 적용한 뒤에 호출되는 초기화 메서드 명
- DestroyMethodName: 빈의 생명주기가 끝나서 제거하기 직전에 호출되는 메서드 명
- Constructor arguments, Properties: 의존관계 주입에서 사용한다. (자바 설정 처럼 팩토리 역할의 빈을 사용하면 없음)
'Spring(스프링) 기초' 카테고리의 다른 글
| 컴포넌트 스캔과 의존관계 자동 주입 (0) | 2023.12.08 |
|---|---|
| 스프링 싱글톤 컨테이너 (0) | 2023.12.08 |
| 스프링 핵심 원리 이해2 - 객체 지향 원리 적용 (0) | 2023.12.08 |
| 스프링 핵심 원리 이해1 - 예제 만들기 (0) | 2023.12.08 |
| 객체 지향 설계와 스프링 (1) | 2023.12.08 |