Spring Bean Container는 스프링에서 객체(Bean)를 생성, 관리, 의존성 주입(DI), 생명주기 관리 등을 담당하는 핵심 컨테이너입니다.
스프링 애플리케이션 실행 시, 설정에 따라 Bean을 생성하고 필요한 곳에 주입하여 객체 간의 결합도를 낮추고 유지보수성을 향상시킵니다.
💡 Bean이란?
@Component, @Service, @Repository, @Controller 등으로 선언 가능 @Bean을 통해 수동으로 등록 가능 Spring에서는 두 가지 주요 Bean Container를 제공합니다.
| 종류 | 설명 |
|---|---|
| BeanFactory | 가장 기본적인 컨테이너, Lazy Loading 지원 |
| ApplicationContext | BeanFactory 기능 포함, 추가 기능 지원 (이벤트, 국제화 등) |
org.springframework.beans.factory.BeanFactory 인터페이스 제공 org.springframework.context.ApplicationContext 인터페이스 제공 <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
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userService" class="com.example.UserService"/>
</beans>
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean("userService", UserService.class);
@Configuration
public class AppConfig {
@Bean
public UserService userService() {
return new UserService();
}
}
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
UserService userService = context.getBean(UserService.class);
@Component
public class UserService {
public void execute() {
System.out.println("UserService 실행");
}
}
@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {
}
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
UserService userService = context.getBean(UserService.class);
userService.execute();
Spring Bean은 생성 → 초기화 → 사용 → 소멸의 과정을 거칩니다.
| 메서드 | 설명 |
|---|---|
@PostConstruct | Bean 생성 후 초기화 수행 |
@PreDestroy | Bean 소멸 전에 정리 작업 수행 |
init-method | XML 설정에서 초기화 메서드 지정 |
destroy-method | XML 설정에서 소멸 메서드 지정 |
@Component
public class MyBean {
@PostConstruct
public void init() {
System.out.println("Bean 초기화 작업");
}
@PreDestroy
public void destroy() {
System.out.println("Bean 소멸 전 작업");
}
}
@Component
@Scope("singleton") // (기본값, 생략 가능)
public class SingletonBean {
}
@Scope("prototype") 설정 필요 @Component
@Scope("prototype")
public class PrototypeBean {
}
Spring Bean Container를 이해하면 객체 생성과 관리가 자동화되어 코드의 유지보수성이 높아진다는 점을 다시 한번 확인할 수 있었습니다.
@Component와 @Bean을 활용한 설정 방식이 실제 프로젝트에서 많이 사용된다는 점을 알게 되었고 싱글톤과 프로토타입 스코프의 차이를 활용하여 메모리 관리와 성능 최적화를 고려하는 것이 중요함을 깨달았습니다.