2023. 4. 25. 12:20ㆍSpring Framework/Spring IoC
🌿 Spring IoC 컨테이너
Spring Framework의 핵심은 객체의 생성과 조립을 외부에서 관리하는 IoC (Inversion of Control) 컨테이너입니다. 본 포스트에서는 Spring IoC 컨테이너의 개요, 다양한 구성 방식, 설정 메타데이터, 그리고 실제 사용법까지 다룹니다. 🔍
1. 🧠 Spring IoC 컨테이너란?
Spring에서 IoC 컨테이너는 ApplicationContext 인터페이스를 통해 구현되며, 다음 역할을 담당합니다:
- 객체(Bean) 생성 및 구성
- 의존성 주입(Dependency Injection)
- Bean 간의 관계 조립
ApplicationContext context = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
다음 다이어그램은 Spring의 작동 방식을 개략적으로 보여줍니다. 여러분들의 애플리케이션 클래스들은 구성 메타데이터와 결합되어 ApplicationContext 생성 및 초기화 후 완전히 구성되고 실행 가능한 시스템 또는 애플리케이션을 갖게 됩니다.
2. 🏗️ ApplicationContext의 다양한 구현체
Spring Core에 포함된 대표적인 구현체는 다음과 같습니다:
구현체 | 용도 |
---|---|
ClassPathXmlApplicationContext |
classpath에 위치한 XML 설정 사용 |
FileSystemXmlApplicationContext |
파일 시스템의 XML 경로 사용 |
AnnotationConfigApplicationContext |
Java Config 기반 |
GenericApplicationContext |
유연한 reader 조합 가능 |
GenericGroovyApplicationContext |
Groovy DSL 구성용 컨텍스트 |
3. 📄 구성 메타데이터 구성 방식
✅ Java 기반 구성
@Configuration
,@Bean
,@Import
,@DependsOn
을 활용
@Configuration
public class AppConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
}
}
✅ 애노테이션 기반 구성
@Component
public class MyService { ... }
✅ XML 구성
<beans>
<bean id="myService" class="com.example.MyServiceImpl"/>
</beans>
4. 📦 Bean 정의와 계층적 구성
🧩 다중 XML 구성
- ClassPathXmlApplicationContext 생성자로 다수 파일 로드
ApplicationContext ctx = new ClassPathXmlApplicationContext("services.xml", "daos.xml");
<import/>
태그로 외부 설정 병합
<beans>
<import resource="services.xml"/>
<import resource="resources/messageSource.xml"/>
</beans>
⚠️ ../
경로는 피하세요. classpath 루트가 바뀌면 해석 실패 위험이 있습니다.
5. 🧾 XML 구성 상세 예시
✅ 서비스 계층 (services.xml)
<bean id="petStore" class="org.springframework.samples.jpetstore.services.PetStoreServiceImpl">
<property name="accountDao" ref="accountDao"/>
<property name="itemDao" ref="itemDao"/>
</bean>
✅ DAO 계층 (daos.xml)
<bean id="accountDao" class="org.springframework.samples.jpetstore.dao.jpa.JpaAccountDao"/>
<bean id="itemDao" class="org.springframework.samples.jpetstore.dao.jpa.JpaItemDao"/>
6. 🧪 Groovy 기반 구성
beans {
dataSource(BasicDataSource) {
driverClassName = "org.hsqldb.jdbcDriver"
url = "jdbc:hsqldb:mem:grailsDB"
}
sessionFactory(SessionFactory) {
dataSource = dataSource
}
}
ApplicationContext ctx = new GenericGroovyApplicationContext("services.groovy", "daos.groovy");
7. 🧬 GenericApplicationContext를 통한 고급 구성
📘 XML
GenericApplicationContext context = new GenericApplicationContext();
new XmlBeanDefinitionReader(context).loadBeanDefinitions("services.xml", "daos.xml");
context.refresh();
🧾 Groovy
GenericApplicationContext context = new GenericApplicationContext();
new GroovyBeanDefinitionReader(context).loadBeanDefinitions("services.groovy", "daos.groovy");
context.refresh();
✨ 여러 reader들을 동시에 조합하여 다양한 설정 소스를 결합 가능
8. 🛑 getBean() 사용에 대한 경고
PetStoreService service = context.getBean("petStore", PetStoreService.class);
하지만 getBean()
사용은 지양해야 합니다.
스프링 DI의 이상적인 방식은 @Autowired, @Inject 등을 통한 자동 주입입니다.
9. 📚 참고: Resource 추상화
Spring의 Resource
추상화는 URI 스타일 경로를 통해 다양한 위치에서 설정 파일을 로드하는 기능을 제공합니다.
classpath:/config/services.xml
file:/opt/app/config/daos.xml
"${config.location}/services.xml"
← JVM 시스템 속성을 통한 추상화
✅ 정리
항목 | 설명 |
---|---|
ApplicationContext | IoC 컨테이너의 핵심 인터페이스 |
설정 메타데이터 | Java, 애노테이션, XML, Groovy 가능 |
XML import | 모듈별 설정 병합 용이 |
Groovy DSL | Grails 기반 유연한 구성 문법 |
GenericApplicationContext | reader 조합을 통한 동적 구성 |
getBean() |
가능하지만 지양. DI 사용 권장 |
출처 : https://docs.spring.io/spring-framework/reference/core/beans/basics.html
Container Overview :: Spring Framework
As the preceding diagram shows, the Spring IoC container consumes a form of configuration metadata. This configuration metadata represents how you, as an application developer, tell the Spring container to instantiate, configure, and assemble the component
docs.spring.io
'Spring Framework > Spring IoC' 카테고리의 다른 글
Dependencies and Configuration in Detail (0) | 2023.12.10 |
---|---|
Introduction to the Spring IoC Container and Beans (0) | 2023.12.10 |
Fine-tuning Annotation-based Autowiring with @Primary or @Fallback (0) | 2023.07.08 |
Dependency Injection of Spring Framework (0) | 2023.05.01 |
Bean Definition Inheritance (0) | 2023.04.28 |