Spring

Spring Container와 Spring Bean

윤승 2025. 3. 27. 20:13
Spring Container란?
Spring 애플리케이션에서 객체(Bean)를 생성, 관리, 소멸하는 역할을 하는 핵심 요소이다.
애플리케이션이 실행되면 설정 파일이나 Annotation을 읽어 Bean을 생성하고 의존성을 주입하는 과정을 관리한다.

일반적으로 Java에서는 객체를 직접 new 키워드로 생성한다.

 

▼Java에서 객체를 생성하는 방법

MyService myService = new MyService();

 

➡️ 하지만 이 방식은 객체 간의 결합도가 높아지고 유지보수가 어려워지는 문제가 있다.

 

 

🔥 Spring Container의 역할

 

Spring Container는 객체를 직접 생성하지 않고 Spring이 대신 객체(Bean)를 생성하고 관리한다.

ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
MyService myService = context.getBean(MyService.class);

 

  • 필요한 객체를 직접 생성하지 않아도 됨 (객체 생성을 Spring이 담당)
  • 의존성 주입(DI, Dependency Injection)을 통해 객체 간 결합도를 낮출 수 있음
  • OCP(개방-폐쇄 원칙), DIP(의존성 역전 원칙)을 준수하는 구조를 만들 수 있음

🛠 코드를 적용한 예제

1. AppConfig 설정 파일

@Configuration // Spring 설정 클래스 선언
public class AppConfig {

    @Bean // MyService를 Bean으로 등록
    public MyService myService() {
        return new MyService();
    }
}

 

2. MyService 클래스

public class MyService {
    public void doSomething() {
        System.out.println("Spring Bean 동작!");
    }
}

 

3. Main 실행 코드

public class Main {
    public static void main(String[] args) {
        // ApplicationContext(Spring Container) 생성
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

        // Spring Container에서 MyService Bean을 가져옴
        MyService myService = context.getBean(MyService.class);

        // Bean 사용
        myService.doSomething();
    }
}

 

실행결과

 

Spring Bean 동작!

 

➡️ context.getBean(MyService.class)를 사용하면 Spring이 관리하는 Bean을 가져와 사용할 수 있다.

 

 

🔥 Spring Container의 종류

 

Spring Container 설명
BeanFactory 가장 기본적인 컨테이너, Bean을 관리하고 조회하는 역할
ApplicationContext BeanFactory 기능 + 다양한 부가 기능 (국제화, 이벤트, 리소스 관리 등)

 

Spring에서 제공하는 Container는 크게 BeanFactoryApplicationContext가 있다.

 

실제 개발에서는 ApplicationContext를 사용한다. 보통 Spring Container라고 하면 ApplicationContext를 의미함.

 

 

 

 


 

Spring Bean이란?
Spring Container가 관리하는 객체를 Spring Bean이라고 한다.
즉, 일반적인 Java 객체라도 Spring이 관리하면 Bean이 된다.

🔥 Spring Bean의 특징

 

  • Spring Container가 직접 생성하고 관리하는 객체
  • 기본적으로 Singleton(단일 인스턴스)으로 관리됨
  • 의존성 주입(DI)을 통해 다른 객체와 연결됨
  • 생명 주기(생성 → 초기화 → 사용 → 소멸)를 가짐

 


🔥 
Annotation을 이용한 Spring Bean 등록 방법

 

XML 방식도 과거에는 사용되었지만, 현재에는 가장 많이 사용하는 방식이 Annotation을 이용한 방식이다.

 

 

Annotation을 이용한 방법

 

 

1. Spring이 특정 클래스를 Bean으로 인식하도록 @Component 또는 그 하위 어노테이션을 사용한다.

@Component  // Spring이 자동으로 관리하는 Bean으로 등록
public class MyService {
    public void doSomething() {
        System.out.println("Spring Bean 동작!");
    }
}

 

 

2. 의존성 주입은 @Autowired를 사용해 자동으로 연결할 수 있다.

@Component
public class MyApp {
    private final MyService myService;

    @Autowired  // MyService 객체를 자동으로 주입
    public MyApp(MyService myService) {
        this.myService = myService;
    }

    public void run() {
        myService.doSomething();
    }
}

 

 

3. Spring이 Bean을 찾을 수 있도록 @ComponentScan을 설정해야 한다.

@Configuration
@ComponentScan(basePackages = "com.example")  // com.example 패키지를 스캔하여 Bean 등록
public class AppConfig {
    public static void main(String[] args) {
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        MyApp app = context.getBean(MyApp.class);
        app.run();
    }
}

 

 


 

🔥 정리

 

Spring Container

  • Bean을 생성하고 관리하는 핵심 시스템
  • 객체 생성 & 의존성 관리 = Spring Container가 대신 처리

Spring Bean

  • Spring이 관리하는 객체
  • @Component, @Service, @Repository 등의 Annotation을 사용해 등록
  • Singleton(기본), 의존성 주입(DI), 생명 주기 관리