🌱 스프링 컨텍스트와 빈 등록하기
🔍 스프링 컨텍스트란?
- 기본적으로 스프링은 애플리케이션에 정의된 객체들을 모르기 때문에, 스프링이 객체를 관리하도록 하려면 스프링 컨텍스트에 등록해야 합니다.
- 스프링이 관리할 객체 인스턴스를 추가할 수 있는 앱 메모리의 공간
- 컨텍스트에 등록된 객체를 빈(Bean) 이라고 부릅니다.
✅ 빈 등록 방식 3가지
| 등록 방식 | 설명 |
|---|
@Bean 애너테이션 | 구성 클래스 내 메서드로 등록. 인스턴스를 완전히 제어할 수 있음 |
스테레오타입 애너테이션 (@Component) | 클래스에 애너테이션을 붙여 등록. 자동 탐색 |
프로그래밍 방식 (registerBean()) | 코드로 직접 객체를 생성하고 등록 |
1️⃣ @Bean 애너테이션을 사용한 빈 등록
💡 클래스 정의
public class Parrot {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
🧩 구성 클래스 정의
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ProjectConfig {
@Bean
public Parrot parrot() {
Parrot p = new Parrot();
p.setName("국민");
return p;
}
}
🛠 스프링 컨텍스트 초기화 및 빈 사용
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class TestSpringApplication {
public static void main(String[] args) {
var context = new AnnotationConfigApplicationContext(ProjectConfig.class);
Parrot parrot = context.getBean(Parrot.class);
System.out.println(parrot.getName());
}
}
2️⃣ @Component 스테레오타입 애너테이션 사용
💡 클래스 정의 (자동 탐색 대상)
import org.springframework.stereotype.Component;
import jakarta.annotation.PostConstruct;
@Component
public class Parrot {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@PostConstruct
public void init() {
this.name = "국민";
}
}
🧩 구성 클래스 정의
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = "org.example.testspring.config")
public class ProjectConfig {
}
🛠 실행
public class TestSpringApplication {
public static void main(String[] args) {
var context = new AnnotationConfigApplicationContext(ProjectConfig.class);
Parrot parrot = context.getBean(Parrot.class);
System.out.println(parrot.getName());
}
}
🔎 @PostConstruct를 사용하면 스프링이 빈 초기화 후 init() 메서드를 자동 실행해줍니다.
3️⃣ registerBean()으로 프로그래밍 방식 등록
💡 클래스 정의
public class Parrot {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
🧩 구성 클래스 (비어있어도 가능)
import org.springframework.context.annotation.Configuration;
@Configuration
public class ProjectConfig {
}
🛠 빈 직접 등록
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.util.function.Supplier;
public class TestSpringApplication {
public static void main(String[] args) {
var context = new AnnotationConfigApplicationContext(ProjectConfig.class);
Parrot parrot = new Parrot();
parrot.setName("국민");
Supplier<Parrot> parrotSupplier = () -> parrot;
context.registerBean("parrot", Parrot.class, parrotSupplier);
Parrot p = context.getBean(Parrot.class);
System.out.println(p.getName());
}
}
✅ 등록 방식 비교
| 항목 | @Bean 사용 | @Component 사용 |
|---|
| 객체 제어 | 직접 제어 가능 | 스프링이 생성 후 제어 |
| 등록 가능 수 | 여러 개 가능 | 클래스당 1개 등록 |
| 기본 타입 등록 | 가능 | 불가능 |
| 명시성 | 메서드 명시 필요 | 클래스에 애너테이션만 붙이면 됨 |