신비한 개발사전
IoC 컨테이너와 Spring 컨텍스트 본문
Spring 프레임워크는 개발자를 대신해 직접 객체를 생성하고 주입하는 등의 관리 작업을 수행할 수 있다. 이렇게 Spring이 직접 관리하는 객체를 Spring bean이라고 하며, Spring bean의 생애주기와 의존성이 관리되는 곳을 IoC 컨테이너라고 한다.
ApplicationContext
IoC 컨테이너는 스프링 프레임워크 내에서도 bean 관리를 중점적으로 맡는 컴포넌트라고 생각할 수 있다. ApplicationContext는 IoC 컨테이너의 개념을 코드로 옮긴 것으로, Spring bean을 설정, 생성 및 조합하는 기능들을 정의하는 인터페이스다.
The interface org.springframework.context.ApplicationContext represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the aforementioned beans.
(Spring 공식문서 참고)
최상위 단의 ApplicationContext 인터페이스는 읽기 전용 인터페이스로, 실질적으로 bean을 설정하고 등록하는 저수준 기능은 구현체에 있다.
일반적으로 Spring 애플리케이션이 가동될 땐 하나의 컨텍스트가 생성되지만, 필요에 따라 수동으로 컨텍스트를 생성할 수 있다.
ApplicationContext를 통한 빈 제어
StaticApplicationContext와 같은 구현체를 사용하면 런타임 때 bean을 등록하는 코드를 구현할 수 있다.
@Test
void registerBeanWithRegisterSingleton() {
// IoC 컨테이너 생성
StaticApplicationContext context = new StaticApplicationContext();
// Hello 클래스를 싱글톤 bean으로 컨테이너에 등록
context.registerSingleton("hello", Hello.class);
Hello hello = context.getBean("hello", Hello.class);
assertThat(hello).isNotNull();
}
Bean은 컨텍스트 내에서 가지는 이름, 의존하고 있는 다른 bean, 본인이 상속하는 부모 bean 등의 메타정보를 가질 수 있다. 이러한 정보는 BeanDefinition에 저장되는데, ApplicationContext를 통해 등록할 수 있다.
@Test
void registerBeanWithBeanDefinition() {
// IoC 컨테이너 생성
StaticApplicationContext context = new StaticApplicationContext();
// Bean 메타정보를 담은 오브젝트 생성
BeanDefinition helloDef = new RootBeanDefinition(Hello.class);
// Bean 프로퍼티 설정
helloDef.getPropertyValues().addPropertyValue("name", "Spring");
// Bean 메타정보를 hello 라는 이름으로 컨테이너에 등록
context.registerBeanDefinition("hello", helloDef);
Hello hello = context.getBean("hello", Hello.class);
assertThat(hello).isNotNull();
}
ApplicationContext를 활용해 런타임에서 bean을 제어하는 로직을 작성할 수 있지만, 그 필요성에 대해 고민해보면 좋을 것 같다.
'Backend' 카테고리의 다른 글
@Configuration 애노테이션의 주요 목적 (0) | 2025.04.28 |
---|---|
컴포넌트 스캔과 Spring bean 주입 방식 (0) | 2025.04.25 |
객체 생성 시 유의해야 하는 Spring의 의존성 주입 시점 (0) | 2025.04.21 |
H2 데이터베이스 시작하기 (0) | 2025.04.20 |
Spring MVC 컨트롤러의 기본 동작을 구현하는 방법 (0) | 2025.04.18 |