개발자 '쑥말고인절미'
스프링 컨테이너 BeanFactory와 ApplicationContext 본문
스프링 컨테이너
- 자바 객체의 생명 주기를 관리하고, 생성된 자바 객체들에게 추가적인 기능을 제공하는 역할
- 스프링에서 자바 객체를 빈(Bean)이라 부르고, IoC와 DI의 원리가 이 스프링 컨테이너에 적용된다.
- 객체들 간의 의존 관계를 스프링 컨테이너가 런타임 과정에서 알아서 만들어준다.
+ DI는 생성자, setter, @Autowired를 통해 적용한다.
스프링 컨테이터의 종류
1. BeanFactory
- 빈을 등록하고 생성하고 조회하고 돌려주는 등 빈을 관리하는 역할
- getBean() 메소드를 통해 빈을 인스턴스화할 수 있다.
- @Bean이 붙은 메소드 명을 스프링 빈의 이름으로 사용하여 빈 등록을 한다.
@Configuration
public class AppConfig {
@Bean
public OrderService orderService() {
return new OrderServiceImpl(discountPolicy());
}
@Bean
public FixDiscountPolicy discountPolicy() {
return new FixDiscountPolicy();
}
}
- 아래와 같이 BeanFactory를 AnnotationConfigApplicationContext로 정의하되, AppConfig를 구성 정보로 지정한다. 기존에는 개발자가 직접 AppConfig를 사용해서 필요한 객체를 직접 조회했지만, 스프링 컨테이너를 통해서 필요한 스프링 빈 객체를 찾을 수 있다.
public class Main {
public static void main(String[] args) {
final BeanFactory beanFactory = new AnnotationConfigApplicationContext(AppConfig.class);
final OrderService orderService = beanFactory.getBean("orderService", OrderService.class);
final Order order = orderService.createOrder(15, "샤프", 3000);
System.out.println(order.getDiscountPrice());
}
}
2. ApplicationContext
ApplicationContext도 BeanFactory처럼 빈을 관리할 수 있다.
Main 코드에서 BeanFactory를 ApplicationContext로만 바꾸고 실행하면 동일하게 작동한다.
public class Main {
public static void main(String[] args) {
final ApplicationContext beanFactory = new AnnotationConfigApplicationContext(AppConfig.class);
final OrderService orderService = beanFactory.getBean("orderService", OrderService.class);
final Order order = orderService.createOrder(15, "샤프", 3000);
System.out.println(order.getDiscountPrice());
}
}
BeanFactory와 ApplicationContext 비교
- ApplicationContext는 BeanFactory의 상속을 받았다. BeanFactory 자체에 완전하게 상속을 받은 것은 아니지만 빈을 관리하는 기능을 물려받은 것은 맞다.
- ApplicationContext는 그 외에도 국제화가 지원되는 텍스트 메시지 관리, 이미지같은 파일 자원을 로드, 리스너로 등록된 빈에게 이벤트 발생 알림 등 부가적인 기능을 갖고 있다.
- 그래서 스프링 컨테이너하면 주로 이 ApplicationContext를 뜻한다.
- BeanFactory는 처음으로 getBean() 메소드가 호출된 시점에서야 해당 빈을 생성
- ApplicationContext는 Context 초기화 시저멩 모든 싱글톤 빈을 미리 로드한 후 애플리케이션 가동 후에는 빈을 지연없이 받을 수 있다.
- 부가 기능과 빈을 지연없이 얻을 수 있다는 장점으로 ApplicationContext를 실제 개발에서 주로 사용한다.
참고링크
https://steady-coding.tistory.com/459
[Spring] 스프링 컨테이너와 빈이란?
안녕하세요? 제이온입니다. 오늘은 스프링 컨테이너와 빈에 대해서 알아 보겠습니다. 스프링 컨테이너란? 스프링 컨테이너는 자바 객체의 생명 주기를 관리하며, 생성된 자바 객체들에게 추가
steady-coding.tistory.com
'STUDY > Spring & SpringBoot' 카테고리의 다른 글
[Spring] Mapper.java와 Mapper.xml 설명 참고링크 (0) | 2022.11.29 |
---|---|
[Spring] maven, pom.xml에 대하여 (0) | 2022.11.26 |
스프링 및 스프링 부트 어노테이션 정리(1) (0) | 2022.11.19 |
스프링 프레임워크 시작하기 (0) | 2022.10.29 |
[메모] IntelliJ 처음 프로젝트 실행 시 오류 발생 참고링크 (0) | 2022.10.22 |