25.02.04 TIL Spring Bean Container

신성훈·2025년 2월 4일

TIL

목록 보기
128/162

1. Spring Bean Container란?

Spring Bean Container스프링에서 객체(Bean)를 생성, 관리, 의존성 주입(DI), 생명주기 관리 등을 담당하는 핵심 컨테이너입니다.
스프링 애플리케이션 실행 시, 설정에 따라 Bean을 생성하고 필요한 곳에 주입하여 객체 간의 결합도를 낮추고 유지보수성을 향상시킵니다.

💡 Bean이란?

  • Spring이 관리하는 객체
  • @Component, @Service, @Repository, @Controller 등으로 선언 가능
  • @Bean을 통해 수동으로 등록 가능

2. Bean Container의 종류

Spring에서는 두 가지 주요 Bean Container를 제공합니다.

종류설명
BeanFactory가장 기본적인 컨테이너, Lazy Loading 지원
ApplicationContextBeanFactory 기능 포함, 추가 기능 지원 (이벤트, 국제화 등)

(1) BeanFactory

  • org.springframework.beans.factory.BeanFactory 인터페이스 제공
  • Lazy Initialization(지연 초기화): 실제 요청이 있을 때 Bean을 생성
  • 메모리 절약 가능하지만, 대규모 애플리케이션에서는 ApplicationContext 권장

(2) ApplicationContext

  • org.springframework.context.ApplicationContext 인터페이스 제공
  • BeanFactory 기능 포함 + 추가 기능 제공
  • Eager Initialization(즉시 초기화): 컨테이너가 로딩될 때 미리 Bean 생성
  • 국제화(MessageSource), 이벤트, AOP 등 다양한 기능 지원
  • 일반적으로 대부분의 스프링 애플리케이션에서 사용

3. Bean Container 설정 방법

(1) XML 기반 설정 (Bean 등록)

<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);

(2) Config 설정

@Configuration
public class AppConfig {
    @Bean
    public UserService userService() {
        return new UserService();
    }
}
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
UserService userService = context.getBean(UserService.class);

(3) Component Scan 방식 (@Component 활용)

@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();

4. Bean의 라이프사이클

Spring Bean은 생성 → 초기화 → 사용 → 소멸의 과정을 거칩니다.

(1) Bean 라이프사이클 주요 메서드

메서드설명
@PostConstructBean 생성 후 초기화 수행
@PreDestroyBean 소멸 전에 정리 작업 수행
init-methodXML 설정에서 초기화 메서드 지정
destroy-methodXML 설정에서 소멸 메서드 지정

(2) 예제

@Component
public class MyBean {

    @PostConstruct
    public void init() {
        System.out.println("Bean 초기화 작업");
    }

    @PreDestroy
    public void destroy() {
        System.out.println("Bean 소멸 전 작업");
    }
}

5. Singleton vs Prototype

(1) Singleton (기본 설정)

  • 하나의 Bean 인스턴스를 생성하여 공유 (디폴트 설정)
  • 요청할 때마다 같은 객체 반환
@Component
@Scope("singleton")  // (기본값, 생략 가능)
public class SingletonBean {
}

(2) Prototype

  • 요청할 때마다 새로운 객체를 생성
  • @Scope("prototype") 설정 필요
@Component
@Scope("prototype")
public class PrototypeBean {
}

6. 마무리

Spring Bean Container를 이해하면 객체 생성과 관리가 자동화되어 코드의 유지보수성이 높아진다는 점을 다시 한번 확인할 수 있었습니다.
@Component@Bean을 활용한 설정 방식이 실제 프로젝트에서 많이 사용된다는 점을 알게 되었고 싱글톤과 프로토타입 스코프의 차이를 활용하여 메모리 관리와 성능 최적화를 고려하는 것이 중요함을 깨달았습니다.

profile
조급해하지 말고, 흐름을 만들고, 기록하면서 쌓아가자.

0개의 댓글