1) 생명주기 ( Life Cycle) 란 ?

  • 스프링 빈은 스프링 컨테이너 내부에서 생성되고, 스프링이 종료되기 전까지 생명주기 ( Life Cycle) 를 갖는다
  • 이때, 스프링은 객체 생성 -> 의존관계 주입의 라이프 사이클을 갖는다

 

생성 - 설정 - 사용 - 소멸

 

  • 생성

GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();

 

컨테이너와 빈 객체 동시 생성 방법

GenericXmlApplicationContext ctx = new GenericXmlApplicationContext("classpath:appCtx.xml");

 

  • 설정

 

  • 사용

getBean()을 이용한 Bean 객체 사

BookRegisterService bookRegisterService = ctx.getBean("bookRegisterService", BookRegisterService.class);

BookSearchService bookSearchService = ctx.getBean("bookSearchService", BookSearchService.class);

  • 종료

close() 를 이용한 컨테이너 종료

bean 도 함께 소멸

 

ctx.close();

 

 

2) Bean 객체 생명 주기

  • Bean 객체의 생명주기는 스프링 컨테이너의 생명주기와 동일하다
  • 스프링 컨테이너를 생성할때 Bean이 같이 생성되고, getBean()은 생성된 Bean 객체를 불러오는 것

 

3) Bean 객체 생명 주기 사용법

1. interface 활용

  • <interface> InitializingBean 에서 afterPropertiesSet 을 제공 (bean 객체 생성 시 호출)
  • <interface> DisposableBean 에서 destroy 를 제공 (bean 객체 소멸 시 호출)

 

2. init-method, destory-method 속성 활용

 

 

- 스프링 설정 파일 appCtx.xml

<bean id="bookRegisterService" class="com.brms.book.service.BookRegisterService"

init-method="initMethod" destroy-method="destroyMethod"/>

 

 

- BookRegisterService.java

public class BookRegisterService {

 

@Autowired

private BookDao bookDao;

 

public BookRegisterService() { }

 

public void register(Book book) {

bookDao.insert(book);

}

 

public void initMethod() {

System.out.println("BookRegisterService 빈(Bean)객체 생성 단계");

}

 

public void destroyMethod() {

System.out.println("BookRegisterService 빈(Bean)객체 소멸 단계");

}

}

 

 

3.@PostConstruct, @PreDestory 어노테이션 활용

 

+ Recent posts