[Spring] Spring의 핵심 개념

이연우·2025년 7월 25일

TIL

목록 보기
43/100

🧰 Spring Container란?

  • Spring 애플리케이션의 중앙 관리자로서
    객체(Bean)를 만들고, 관리하고, 서로 연결(의존성 주입)하고, 생명주기를 책임지는 역할을 함

Java의 객체 생성

  • 사용하는 클래스에서 직접 생성

Spring Container의 역할

  • 객체(Bean)를 생성 및 관리하고 의존성을 주입하는 역할을 담당

🔧 객체 생성 방식의 차이

방식설명단점
Java 일반 방식new 키워드로 직접 생성객체 간 결합도가 높음
Spring 방식컨테이너가 대신 생성 및 주입결합도 낮고 유연함 (OCP, DIP 준수)

👨‍🍳 Spring Container 비유: 주방의 셰프

  • 개발자요리를 주문만 하고,
    Spring Container(셰프)재료(Bean)를 선택하고, 조리(생성 및 주입) 후 제공한다.
    → 필요한 객체를 직접 만들지 않고, Container가 필요한 시점에 주입
    → 덕분에 재료가 바뀌어도(클래스 변경) 요리법을 바꿀 필요 없음

🧱 Spring Container의 종류

종류설명특징
BeanFactory가장 단순한 컨테이너Bean 생성 및 조회만 담당
ApplicationContext실제로 많이 사용하는 컨테이너국제화, 이벤트, 리소스 처리 등 다양한 기능 추가

💡 보통 Spring Container = ApplicationContext라고 말함


📚 Spring Bean (스프링 빈)이란?

  • Spring Container가 직접 생성하고 관리하는 객체
  • 단순 Java 객체이지만, Spring이 관리하는 순간부터 Bean이라고 부름
    Beannew 키워드 대신 사용하는 것

🧂 Spring Bean 비유: 요리 재료

  • Spring Container(셰프)가 요리를 하기 위해 준비한 재료가 Bean
    → 이 재료들은 모두 Spring이 직접 골라 관리

🌟 Spring Bean의 특징

특징설명
생성Container가 new 대신 객체 생성
생명주기생성 → 초기화 → 사용 → 소멸
싱글톤기본적으로 Bean은 하나만 생성되어 공유됨
의존성 주입다른 객체가 필요할 경우 자동으로 연결해줌 (DI)

✅ Spring Bean 등록 방법

1. XML 방식 (구 방식)

<beans>
    <!-- myBean이라는 이름의 Bean 정의 -->
    <bean id="myBean" class="com.example.MyBean" />
</beans>
public class MyApp {
    public static void main(String[] args) {
        // Spring 컨테이너에서 Bean을 가져옴
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        MyService myService = context.getBean("myBean", MyBean.class);
        myService.doSomething();
    }
}

→ 요즘은 잘 쓰지 않지만, XML 설정도 가능

2. 어노테이션 방식 (많이 사용됨)

  • @ComponentScan
// 이 클래스를 Bean으로 등록
// @Controller, @Service, @Repository
@Component
public class MyService {

    public void doSomething() {
        System.out.println("Spring Bean 으로 동작");
    }
    
}
@Component
public class MyApp {

    private final MyService myService;

    @Autowired // 의존성 자동 주입
    public MyApp(MyService myService) {
        this.myService = myService;
    }

    public void run() {
        myService.doSomething();
    }
}
// com.example 패키지를 스캔하여 Bean 등록
@Configuration
@ComponentScan(basePackages = "com.example")
public class AppConfig {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        MyApp app = context.getBean(MyApp.class);
        app.run();
    }
    
}

@Component, @Service, @Repository, @Controller 등으로 Bean 등록
@Autowired를 통해 의존성 자동 주입

3. 자바 설정 파일 방식 (명시적 등록)

@Configuration
public class AppConfig {

    @Bean
    public MyService myService() {
        return new MyService();
    }
}
public class MyApp {
    public static void main(String[] args) {
        // Spring 컨테이너에서 Bean을 가져옴
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        MyService myService = context.getBean(MyService.class);
        myService.doSomething();
    }
}

→ Java 코드로 Bean을 등록하고 직접 제어할 수 있음
→ 명시적인 Bean 정의가 필요한 경우 적합

0개의 댓글