개발일지/Spring

Spring Bean

꾸주니=^= 2025. 2. 7. 09:43


🏗️📌 Spring Bean이란?

Spring에서 Bean(빈)이란 Spring 컨테이너가 생성하고 관리하는 객체를 의미합니다.
즉, 일반적인 Java 객체이지만 Spring이 직접 생성하고 관리하며, 의존성 주입(DI)이 적용된 객체입니다.

💡 왜 Spring Bean을 사용할까?

  • 객체를 Spring이 직접 관리하므로 개발자는 객체 생성과 의존성 주입을 신경 쓰지 않아도 됩니다.
  • 싱글톤 패턴이 기본 적용되어 불필요한 객체 생성을 방지하고 성능을 최적화합니다.
  • 객체 간의 관계(의존성)를 명확하게 설정할 수 있습니다.

 


🏗️ 1️⃣ Spring Bean 등록 방법

Spring Bean을 등록하는 방법은 크게 3가지가 있습니다.

✅ 1. @Component + @ComponentScan (자동 등록)

Spring Boot에서는 @Component를 사용하여 자동으로 Bean을 등록할 수 있습니다.

import org.springframework.stereotype.Component;

@Component // 자동으로 Spring Bean으로 등록됨
public class MemberService {
    public void join() {
        System.out.println("회원 가입 완료!");
    }
}

💡 Spring Boot에서는 @ComponentScan이 기본 활성화되어 @Component가 붙은 클래스를 자동으로 빈으로 등록합니다.
@SpringBootApplication 내부에 @ComponentScan이 포함되어 있기 때문에 추가 설정 없이 사용 가능합니다.

 

✅ 2. @Configuration + @Bean (수동 등록)

클래스를 설정 파일(@Configuration)로 만들고, 직접 @Bean을 사용하여 객체를 생성하고 관리할 수도 있습니다.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration // 설정 파일임을 나타냄
public class AppConfig {

    @Bean // Spring 컨테이너가 이 메서드를 실행하여 Bean을 생성함
    public MemberService memberService() {
        return new MemberService();
    }
}

💡 이 방식은 명확한 의존성 설정이 필요할 때 유용하며, 인터페이스 기반의 설계를 지원할 때 좋습니다.

 

✅ 3. XML 설정 (applicationContext.xml)

과거에는 XML 파일을 이용해 Bean을 설정했습니다.
하지만 Java 기반 설정(@Configuration + @Bean)이 등장하면서 거의 사용되지 않습니다.

<bean id="memberService" class="com.example.MemberService"/>

💡 Spring Boot에서는 XML 설정을 거의 사용하지 않으며, Java 기반 설정이 표준입니다.

 


🎯 2️⃣ Spring Bean 사용 방법

Spring Bean을 사용하려면 Spring 컨테이너(ApplicationContext)를 통해 가져와야 합니다.

 ApplicationContext를 사용하여 Bean 가져오기

import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
    public static void main(String[] args) {
        // AppConfig.class에서 Bean 설정을 로드
        ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

        // Bean 가져오기
        MemberService memberService = context.getBean("memberService", MemberService.class);
        memberService.join();
    }
}

💡 ApplicationContext는 Spring 컨테이너 역할을 하며, Bean을 검색하고 주입하는 기능을 제공합니다.

 


🔄 3️⃣ Spring Bean의 기본 동작 원리

1. Spring 컨테이너가 생성됨

Spring Boot 애플리케이션이 실행되면 Spring 컨테이너(ApplicationContext)가 생성됩니다.
이 컨테이너는 Bean을 관리하고 의존성을 주입하는 핵심 역할을 합니다.

2. Bean을 등록하고 관리

@Component, @Bean 등이 붙은 객체를 찾아 Spring 컨테이너가 자동으로 싱글톤 객체로 등록합니다.

3. 필요한 곳에 Bean을 주입(DI)

@Autowired를 사용하여 필요한 곳에 Bean을 주입하여 사용 가능합니다.

 


🔌 4️⃣ Spring Bean 주입 방법 (DI)

Spring에서는 의존성 주입(Dependency Injection, DI)을 통해 객체를 자동으로 주입할 수 있습니다.
주입 방식은 3가지가 있습니다.

✅ 1. 생성자 주입 (권장)

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MemberService {
    private final MemberRepository memberRepository;

    @Autowired // 생성자 주입 (Spring Boot에서는 생략 가능)
    public MemberService(MemberRepository memberRepository) {
        this.memberRepository = memberRepository;
    }
}

💡 생성자 주입은 객체가 불변(immutable)하도록 보장하기 때문에 가장 권장되는 방식입니다.

 

✅ 2. 필드 주입 (비추천)

@Service
public class MemberService {
    @Autowired
    private MemberRepository memberRepository;
}

🚨 필드 주입은 권장되지 않음 → 테스트 및 유지보수 어려움

 

✅ 3. Setter 주입 (옵션일 때 사용 가능)

@Service
public class MemberService {
    private MemberRepository memberRepository;

    @Autowired
    public void setMemberRepository(MemberRepository memberRepository) {
        this.memberRepository = memberRepository;
    }
}

💡 Setter 주입은 선택적으로 변경할 수 있는 의존성에 사용 가능하지만, 생성자 주입이 더 안전합니다.

 


🔄 5️⃣ Spring Bean의 스코프(Scope)

Bean은 기본적으로 싱글톤(Singleton) 으로 동작하지만, 여러 개의 인스턴스를 생성해야 할 경우 스코프를 변경할 수 있습니다.

✅ 주요 스코프 종류

스코프 설명
singleton (기본값) 한 개의 Bean 인스턴스만 생성 (전역적으로 공유)
prototype 요청할 때마다 새로운 객체를 생성
request HTTP 요청마다 새로운 Bean 인스턴스를 생성
session HTTP 세션마다 새로운 Bean 인스턴스를 생성

 

✅ Bean 스코프 설정 방법

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype") // 호출할 때마다 새로운 객체 생성
public class PrototypeBean {
}

 


🚀 6️⃣ Spring Bean과 싱글톤 패턴의 차이

Spring Bean의 기본 스코프는 싱글톤(singleton) 이지만, 전통적인 싱글톤 패턴과는 다릅니다.

✅ 싱글톤 패턴 (직접 구현)

public class SingletonService {
    private static final SingletonService instance = new SingletonService();

    private SingletonService() {}

    public static SingletonService getInstance() {
        return instance;
    }
}

🚨 문제점:

  • 직접 객체 생성을 제한해야 함
  • 클라이언트 코드가 getInstance()를 사용해야 함
  • 테스트 및 DI 적용이 어려움

 

✅ Spring 컨테이너의 싱글톤

  • Spring 컨테이너가 객체를 관리하므로 개발자가 직접 싱글톤을 구현할 필요가 없음
  • @Configuration을 사용하면 싱글톤 객체가 자동으로 관리됨

 


🎯 7️⃣ 정리: Spring Bean의 핵심 개념

개념 설명
Spring Bean Spring 컨테이너가 관리하는 객체
등록 방법 @ComponentScan, @Bean, XML
사용 방법 ApplicationContext.getBean()
DI 주입 방식 생성자(권장), 필드(비추천), Setter
스코프 singleton, prototype, request, session
싱글톤 차이 전통적 싱글톤 패턴과 다르게 Spring이 관리