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

Spring Container의 역할

🔧 객체 생성 방식의 차이
| 방식 | 설명 | 단점 |
|---|---|---|
| Java 일반 방식 | new 키워드로 직접 생성 | 객체 간 결합도가 높음 |
| Spring 방식 | 컨테이너가 대신 생성 및 주입 | 결합도 낮고 유연함 (OCP, DIP 준수) |
👨🍳 Spring Container 비유: 주방의 셰프
🧱 Spring Container의 종류

| 종류 | 설명 | 특징 |
|---|---|---|
BeanFactory | 가장 단순한 컨테이너 | Bean 생성 및 조회만 담당 |
ApplicationContext | 실제로 많이 사용하는 컨테이너 | 국제화, 이벤트, 리소스 처리 등 다양한 기능 추가 |
💡 보통 Spring Container = ApplicationContext라고 말함
📚 Spring Bean (스프링 빈)이란?
- Spring Container가 직접 생성하고 관리하는 객체
- 단순 Java 객체이지만, Spring이 관리하는 순간부터 Bean이라고 부름
→ Bean은 new 키워드 대신 사용하는 것
🧂 Spring Bean 비유: 요리 재료
🌟 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 정의가 필요한 경우 적합