WebServer/Spring
[Spring] 빈 생명주기(LifeCycle) 콜백 메서드
gangintheremark
2023. 9. 12. 22:04
728x90
스프링의 IoC 컨테이너는 빈 객체의 생성부터 소멸까지의 생명주기(LifeCycle)
관리를 한다. 특정 이벤트가 발생하면 시스템이 자동으로 호출되는 콜백 메서드
를 제공하고 있으며 이를 통해 LifeCycle에 따른 빈 객체의 상태를 정교하게 제어할 수 있다.
생명주기 콜백 메서드 사용 방법
- 인터페이스
InitializionBean
DisposableBean
- 메서드 지정
<bean init-method="메서드명" destroy-method="메서드" />
- 어노테이션
@PostConstruct
@PreDestroy
인터페이스
InitializionBean
인터페이스- 초기화 콜백 메서드 제공
afterPropertiesSet()
: 의존관계 주입이 끝난 후 메서드 호출
DisposableBean
인터페이스- 소멸 콜백 메서드 제공
destroy()
: 스프링 빈 소멸 전에 메서드 호출
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class UserService implements InitializingBean, DisposableBean {
public UserService() {
System.out.println("UserService 생성자");
}
// DisposableBean
@Override
public void destroy() throws Exception {
System.out.println("UserService 소멸");
}
// InitializingBean
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("UserService 생성");
}
}
메서드 지정
- 메서드 이름은 자유롭게 지정
- 빈의 설정 정보 이용
public class UserService {
public UserService() {
System.out.println("UserService 생성자");
}
// init-method
public void init() {
System.out.println("UserService 생성");
}
// destory-method
public void destroy() {
System.out.println("UserService 소멸");
}
}
<!-- Bean Configuration xml file -->
<bean id="service" class="com.service.UserService" init-method="init" destroy-method="destroy" />
어노테이션
- 설정 정보에
<context:annotation-config/>
작성 필수 - JDK 11 부터는 지원X
public class UserService {
public UserService() {
System.out.println("UserService 생성자");
}
@PostConstruct
public void init() {
System.out.println("UserService 생성");
}
@PreDestroy
public void destrooy() {
System.out.println("UserService 소멸");
}
}
728x90