SpringContainer
Spring으로 구성된 애플리케이션에서 객체(Bean)를 생성, 관리, 소멸하는 역할을 담당. 애플리케이션 시작 시, 설정 파일이나 Annotation을 읽어 Bean을 생성하고 주입하는 모든 과정을 컨트롤 한다.
- Java의 객체 생성
- Java의 객체 생성은 new 키워드를 통해 직접 인스턴스를 생성하는 방식이다. 예를 들어, 클래스 A에서 클래스 B의 기능을 사용하려면, A에서 new B()를 통해 B 객체를 직접 생성한다.
- 이 방식은 객체 간 결합도가 높아지고, 객체의 생성 및 관리 책임이 A 클래스에 부여된다.
- Java의 객체 생성은 new 키워드를 통해 직접 인스턴스를 생성하는 방식이다. 예를 들어, 클래스 A에서 클래스 B의 기능을 사용하려면, A에서 new B()를 통해 B 객체를 직접 생성한다.
- SpringContainer의 역할
- 객체(Bean)를 생성 및 관리하고 의존성을 주입하는 역할을 담당한다.
- 예를 들어, A클래스에서 B 클래스의 기능을 쓰고 싶으면 A 클래스에서 인스턴스화 하는 것이 아니라 SpringContainer가 자동으로 B 클래스를 넣어준다.
- SpringConatiner 종류
- BeanFactory
- Spring Container의 최상위 인터페이스
- Spring Bean을 관리하고 조회한다.
- ApplicationContext(일반적으로 이걸 사용하기 떄문에 == SpringContainer로 표현)
- BeanFactory의 확장된 형태(구현체)
- Application 개발에 필요한 다양한 기능을 추가적으로 제공한다.
- 국제화, 환경변수 분리, 이벤트, 리소스 조회
- BeanFactory
SpringBean
Spring Container가 관리하는 객체를 의미. 자바 객체 자체는 특별하지 않지만, Spring이 이 객체를 관리하는 순간부터 Bean이 된다. Spring은 Bean을 생성, 초기화, 의존성 주입 등을 통해 관리.
- SpringBean의 특징
- SpringContainer에 의해 생성되고 관리
- 기본적으로 싱글톤으로 설정
- DI를 통해 다른 객체들과 의존 관계를 맺을 수 있다.
- 생성, 초기화, 사용, 소멸의 생명주기를 가진다.
- Bean 등록 방법
- Annotation
- @Component: 기본적인 Bean 등록
- @Autowired: 의존성 주입 어노테이션으로, 자동으로 의존성을 주입합니다.
- @Service, @Repository, @Controller: 특정 역할을 나타내는 Bean 등록 어노테이션
- Annotation
// 이 클래스를 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();
}
}
}
- Java 설정 파일
@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();
}
}
현대적인 Spring 애플리케이션에서는 애노테이션 기반 빈 등록이 훨씬 더 일반적으로 사용!
SpringBoot에서는 애노테이션 기반의 설정을 많이 사용(더 직관적이고 편리하기 때문에)하고, Java 설정 파일은 필요에 따라 추가저인 제어가 필요할 때 사용된다.
'Back-End > Spring' 카테고리의 다른 글
| Spring Bean 등록 (0) | 2024.12.08 |
|---|---|
| IOC / DI (0) | 2024.12.06 |
| 객체 지향 설계(SOLID 원칙) (1) | 2024.12.06 |
| Spring DI(의존성 주입)에 대해서 (1) | 2024.12.01 |
| Spring Annotation (0) | 2024.12.01 |