Spring/Spring
[Spring][Core] 1. IoC Container
noahkim_
2023. 10. 14. 16:32
1. Introduction to the Spring IoC Container and Beans
IoC (Inversion of Control)
- 전통적으로는 객체 생성, 생명 주기 관리는 개발자가 작성한 코드에 의해 제어됩니다.
- IoC는 이러한 제어 흐름의 주체를 프레임워크나 컨테이너가 담당하도록 하는 매커니즘입니다.
- 프레임워크가 주요 제어 흐름을 담당하게 하여, 개발자가 비즈니스 로직에 집중할 수 있게 합니다.
DI (Dependency Injection)
- IoC의 한 형태로, 객체의 의존성을 외부에서 주입하는 기법입니다.
- 의존성을 개발자가 직접 코드로 주입하는 것이 아닌, IoC Container에 의해 자동으로 주입됩니다.
IoC Container
- Spring에서 객체 생성 및 관리, 의존성 주입을 담당하는 컴포넌트입니다.
- IoC Container의 명세와 구현체가 제공됩니다.
항목 | BeanFactory (org.springframework.beans) |
ApplicationContext (org.springframework.context)
|
역할 | 객체 생성 및 관리 (IoC 컨테이너의 기본) | BeanFactory의 확장 (IoC 컨테이너의 모든 기능 제공) |
초기화 시점 | 지연 초기화 (Lazy Initialization) |
즉시 초기화 (Eager Initialization)
|
AOP 지원 | 제한적 |
통합적인 AOP 기능을 쉽게 사용할 수 있음
|
국제화(i18n) | X |
메시지 리소스 처리 기능 내장 (MessageSource)
|
이벤트 처리 | X |
이벤트 발행 및 리스너 처리 가능 (ApplicationEvent)
|
웹 지원 | X |
웹 애플리케이션 특화 컨텍스트 지원 (WebApplicationContext 등)
|
사용 용도 | 경량 환경 (메모리 민감한 경우) |
대부분의 스프링 애플리케이션에서 표준으로 사용
|
Bean
- 애플리케이션의 핵심 오브젝트입니다. (애플리케이션을 구성하는 실제 객체)
- IoC Container에 의해 생성되고 관리됩니다. (Configuration Metadata를 기반으로 셋팅됨)
2. Container Overview

Configuration Metadata
- Spring Ioc Container 설정 파일
- Configuration Metadata 기반으로 Bean을 생성하고 관리합니다.
- Bean의 객체화, 구성, 조립 방법 등
- 다양한 방식에 따른 ApplicationContext의 구현체가 제공됩니다.
항목 | XML 기반 설정 | Java 기반 설정 |
설정 방식 | XML 파일로 Bean 정의 |
Java 코드로 Bean 정의
|
대표 클래스 | ClassPathXmlApplicationContext FileSystemXmlApplicationContext |
AnnotationConfigApplicationContext
|
Bean 등록 | <bean id="..." class="..."/> |
@Bean, @Component, @Service, @Repository, @Controller
|
의존성 주입 | <property name="..." ref="..."/> |
@Autowired, @Qualifier
|
설정 클래스 지정 | <import resource="..."/> |
@Configuration, @Import, @DependsOn
|
자동 스캔 | <context:component-scan base-package="..."/> |
@ComponentScan(basePackages = "...")
|
파일 위치 | classpath: 또는 filesystem: 경로 지정 |
Java class (e.g., AppConfig.class)
|
장점 | 구조화된 설정 파일로 관리 가능 명시적이고 직관적임 |
타입 안정성 리팩토링 용이 IDE 지원 우수 |
단점 | 가독성 저하 IDE 자동완성 제한 |
복잡성 증가 (Java 코드에 설정이 섞여 있음)
|
xml 예제
더보기
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="services.xml"/>
<import resource="resources/messageSource.xml"/>
<import resource="/resources/themeSource.xml"/>
<bean id="bean1" class="..."/>
<bean id="bean2" class="..."/>
</beans>
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
ApplicationContext context = new FileSystemXmlApplicationContext("C:/spring-config/beans.xml");
Java 예제
더보기
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
출처