🎨 스프링 Container Life Cycle
생성 -> 설정(초기화) -> 사용 -> 종료
의 과정을 거칩니다.
// 생성
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
// 설정
ctx.load("classpath:applicationContext.xml");
ctx.refresh();
// 사용
Blog blog = ctx.getBean("blog", Blog.class);
System.out.println("블로그 주인 :" + blog.getUserName());
System.out.println("블로그 이름 :" + blog.getBlogName());
// 종료
ctx.close();
🎨 스프링 Bean Life Cycle
Container와 동일한 생명주기를 가지고 있습니다.
Container가 초기화 될 때 Bean객체를 등록,생성, 주입하고
Container가 소멸될 때 함께 소멸됩니다.
Bean 초기화 과정에서 InitializingBean 인터페이스의 afterPropertiesSet() 가 호출되고,
Bean 소멸 과정에서 DisposableBean 인터페이스의 destroy() 가 호출됩니다.
Override를 통해 Bean 초기화, 소멸 과정에 개입가능하고, [Bean 객체].destroy()와 같이 사용하여
컨테이너와 별개로 Bean만 소멸시킬 수도 있습니다.
🎨 Spring Bean 이란
일반적으로 '객체'라고 생각하면 됩니다.
ApplicationContext.getBean()으로 얻어질 수 있는 객체는 빈입니다.
즉 Spring에서의 빈은 ApplicationContext가 알고있는 객체, 즉 ApplicationContext가 만들어서 그 안에 담고있는 객체를 의미합니다.
그렇다면, Springboot에서의 Bean 설정은 어떻게 이루어진 걸까요?
보통 @Component 어노테이션을 이용하여 Bean 객체를 등록하는데요.
@Component 어노테이션을 기반으로 @Controller, @Service, @Repository 같은 것들이 확장되어져있습니다.
특정 빈만 팩토리 메소드를 통해 만들고 싶다면 일반 빈 클래스에 @Bean 메소드를 추가하여 사용합니다.
'Spring > 웹' 카테고리의 다른 글
CRUDRepository vs JPARepository 도대체 무슨 차이지? (0) | 2021.04.16 |
---|---|
Servlet (서블릿이란? 그리고, Dispatcher Servlet이란 ? ) (2) | 2021.04.05 |
Container란? (Servlet / Spring Container) (0) | 2021.04.03 |
Lombok의 좋은 사용법 (3) | 2021.03.29 |
AOP란? (Spring AOP) (0) | 2021.03.26 |