Spring BeanCreationNotAllowedException: Singleton Bean 생성 오류와 종료 시점 문제 해결법

1. 오류 메시지

Spring 종료 시 다음과 같은 예외가 발생할 수 있습니다:

org.springframework.beans.factory.BeanCreationNotAllowedException: 
Error creating bean with name 'incomingWebhookGateway': 
Singleton bean creation not allowed while singletons of this factory are in destruction

2. 발생 시점

Spring 애플리케이션 종료 중, 별도 쓰레드 또는 병렬 처리 중에 ApplicationContext.getBean() 을 호출하는 경우에 발생합니다.

예를 들어 다음은 비동기 처리 로직 내에서 Bean을 호출한 경우입니다:

// 샘플 클래스명은 가공된 것임
com.sample.batch.job.SampleOrderJob.processOrders()

3. 주요 원인

  • Spring Context가 종료(destroy) 중임
  • 별도 쓰레드가 Spring Bean을 요청함
  • 이미 Singleton Bean 소멸 중이라 BeanFactory가 새 요청을 차단함

4. 해결 방법

4.1 Bean 사전 주입

가능한 경우 생성자 주입이나 @Autowired 로 Bean을 미리 확보해두세요.

4.2 ExecutorService 종료 처리

Executor를 사용했다면 Spring 종료 시 shutdown() 또는 shutdownNow() 호출을 통해 쓰레드 풀을 정리해야 합니다.

4.3 안전한 Bean 요청 조건 처리

if (applicationContext.isRunning()) {
    MyBean bean = applicationContext.getBean(MyBean.class);
}

5. 요약

항목설명
에러 종류BeanCreationNotAllowedException
원인Spring 종료 중에 BeanFactory에서 Bean을 요청함
영향비동기 처리, 병렬 처리, 배치 작업 등에서 예외 발생 가능
해결책Bean 사전 주입, Executor 종료, Context 접근 제한

6. 마무리

해당 문제는 특히 Spring Batch, 비동기 이벤트 처리, 대규모 병렬 처리가 포함된 시스템에서 자주 발생할 수 있는 문제입니다. Spring의 생명주기와 쓰레드 동기화 전략을 이해하고, 종료 시점의 안전성을 고려하여 시스템을 설계하는 것이 중요합니다.

관련 글

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다