본문 바로가기
Archive/Java 풀스택 아카데미

[TIL] 14. 10월 Spring Framework(Container)

by Lseing 2025. 10. 19.

Spring Container란?

스프링 컨테이너는 스프링의 핵심이다. 스프링 애플리케이션에서 객체(Bean)들을 생성하고 관리하는 컨테이너를 말한다.

왜 컨테이너가 필요하나요?

 

기존 방식(왼쪽)과 Spring Container 방식(오른쪽)

// 기존 방식 - 개발자가 직접 관리
public class StudentController {
    private StudentService service = new StudentService(); // 직접 생성
    private StudentDAO dao = new StudentDAO();             // 직접 생성
    
    // 객체들 사이의 관계도 직접 설정해야 함
}

 

기존방식으로 하면

  • 코드가 복잡해진다.
  • 테스트하기 어렵다
  • 나중에 수정하기 힘들다
  • 메모리 낭비가 발생한다.

하지만 spring container를 사용하면

  • 객체 생성을 자동으로 해준다.
  • 객체들간의 관계도 자동으로 연결해준다.
  • 하나의 객체만 만들어서 공유한다(싱글톤)
  • 테스트하기 쉽다.

이러한 장점이 있다.

Container의 역할

Spring Container의 4가지 역할

1. 객체 생성 - Bean을 자동으로 생성
2. 객체 생명주기 관리 - 생성부터 소멸까지 관리
3. 의존성 주입 - @Autowired로 자동 연결
4. 객체 저장 및 제공 - 필요할 때 꺼내 쓸 수 있게

Container의 동작 원리

1단계: 스프링 애플리케이션 시작

// 서버 시작 시
public static void main(String[] args) {
    SpringApplication.run(MyApp.class, args);
    // Spring Container가 생성됨
}

 

2단계: 클래스 스캔

Container가 프로젝트 전체를 스캔하면서 특정 어노테이션이 붙은 클래스를 찾는다

@Controller  // 발견!
public class StudentController { }

@Service  // 발견!
public class StudentService { }

@Repository  // 발견!
public class StudentDAO { }

 

3단계: 객체 생성

발견한 클래스들의 객체를 생성해서 Container에 저장한다.

// Container 내부에서 실행되는 것 (개발자가 직접 하지 않음)
StudentController controller = new StudentController();
StudentService service = new StudentService();
StudentDAO dao = new StudentDAO();

// Container에 저장
container.put("studentController", controller);
container.put("studentService", service);
container.put("studentDAO", dao);

 

4단계: 의존성 주입

각 객체가 필요로 하는 다른 객체들을 자동으로 연결해준다.

@Controller
public class StudentController {
    @Autowired
    private StudentService service;  
    // Container가: service = container.get("studentService");
}

 

5단계: 애플리케이션 실행

모든 준비가 끝나면 애플리케이션이 정상 작동한다.


Container의 종류

Spring에는 두 가지 주요 Container가 있다.

 

1. BeanFactory

가장 기본적인 Container로 기본 기능만 제공한다.

 

특징

- 가볍고 단순

- Bean을 요청할 때 생성

- 거의 사용하지 않음

 

2. ApplicationContext(주로 사용, 이것만 알면 됨)

BeanFactory를 상속받아 더 많은 기능을 제공한다.

 

특징

- BeanFactory의 모든 기능 포함

- 시작할 때 모든 Bean 생성

- Spring에서 기본적으로 사용하는 Container


SpringMVC에서 Container의 위치

SpringMVC 에서는 Container가 부모-자식 구조로 나뉘어 있다.

 

1. Root ApplicationContext(부모)

역할: 전체 애플리케이션에서 공통으로 사용하는 Bean 관리

ex) Service, DAO, DB 관련 Bean

 

2. Servlet ApplicationContext(자식)

역할: 웹 관련 Bean 관리

ex) Controller, ViewResolver, HandlerMapping

 

관계도

 

자식 Container는 부모 Container의 Bean을 사용할 수 있다.