Spring에서 Bean은 컨테이너에 의해 생성되고 관리되며, 특정 생명주기(Lifecycle)를 따릅니다. Bean의 생명주기를 이해하면 초기화, 자원 해제, 의존성 주입 등의 시점을 명확하게 제어할 수 있습니다.
@Autowired, @Value 등)@PostConstruct 또는 InitializingBean의 afterPropertiesSet() → 초기화 로직@PreDestroy 또는 DisposableBean의 destroy() → 소멸 직전 정리 작업@PostConstruct, @PreDestroy (가장 일반적)@Component
public class MyBean {
@PostConstruct
public void init() {
// 초기화 로직
}
@PreDestroy
public void cleanup() {
// 종료 전 정리 작업
}
}
public class MyBean implements InitializingBean, DisposableBean {
@Override
public void afterPropertiesSet() {
// 초기화 로직
}
@Override
public void destroy() {
// 정리 작업
}
}
@Bean 등록 시 initMethod / destroyMethod 지정@Configuration
public class AppConfig {
@Bean(initMethod = "init", destroyMethod = "close")
public MyBean myBean() {
return new MyBean();
}
}
BeanNameAware: 자신의 Bean 이름 획득BeanFactoryAware: BeanFactory 획득ApplicationContextAware: ApplicationContext 획득이러한 인터페이스들은 스프링 내부의 정보를 사용하고자 할 때 유용합니다.
Spring Bean은 생성 → 의존성 주입 → 초기화 → 사용 → 소멸 단계로 관리되며,
@PostConstruct,@PreDestroy, 인터페이스, initMethod 등을 통해 라이프사이클의 각 단계를 제어할 수 있습니다.