0Pricing
Spring Boot 4 Microservices & REST APIs · 강의

수명 주기 콜백

빈 초기화 및 소멸 단계에 연결해 보세요.

수명 주기 콜백은(는) CoddyKit의 무료 Spring Boot 4 Microservices & REST APIs 강의입니다. 이것은 4개 중 4번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Spring Boot 4 Microservices & REST APIs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Spring Boot 4 Microservices & REST APIs 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

The Bean Lifecycle

Beyond construction, beans pass through phases: the container instantiates them, injects dependencies, runs initialization callbacks, serves requests, then runs destruction callbacks at shutdown.

Hooking into these phases lets you set up and clean up resources reliably.

Why Not Use the Constructor?

A constructor runs before dependencies are injected when using setter/field injection, so collaborators may still be null. Initialization that depends on injected beans belongs in a post-construction callback, not the constructor.

With constructor injection the dependencies are present, but lifecycle callbacks still give a clear, intent-revealing place for setup.

@PostConstruct

A method annotated @PostConstruct runs once after the bean is fully constructed and all dependencies are injected. Use it for warm-up tasks like priming a cache or validating state.

@Service
public class CatalogService {
    private final ProductRepository repo;
    private List<Product> cache;
    public CatalogService(ProductRepository repo) { this.repo = repo; }

    @PostConstruct
    void warmUp() {
        this.cache = repo.findAllActive();
    }
}

@PreDestroy

A method annotated @PreDestroy runs once when the context is shutting down, before the bean is destroyed. Use it to release resources like connections, thread pools, or file handles.

@Service
public class ConnectionManager {
    private final ExecutorService pool = Executors.newFixedThreadPool(4);

    @PreDestroy
    void shutdown() {
        pool.shutdown();
    }
}

The InitializingBean Interface

Implementing InitializingBean provides afterPropertiesSet, called after dependencies are set. It works but couples your class to Spring’s API, so annotations are usually preferred.

@Service
public class IndexService implements InitializingBean {
    @Override
    public void afterPropertiesSet() {
        buildIndex();
    }
}

The DisposableBean Interface

Symmetrically, DisposableBean supplies a destroy method for cleanup. Like InitializingBean, it ties you to Spring interfaces.

@Service
public class IndexService implements DisposableBean {
    @Override
    public void destroy() {
        releaseIndex();
    }
}

@Bean initMethod and destroyMethod

For beans you create with @Bean (often third-party types), specify lifecycle methods by name. This keeps the external class free of Spring annotations.

@Bean(initMethod = "start", destroyMethod = "stop")
public CacheClient cacheClient() {
    return new CacheClient(config);
}

Ordering of Callbacks

When several mechanisms are present, the init order is: @PostConstruct first, then InitializingBean.afterPropertiesSet, then a custom initMethod. Destruction mirrors this with @PreDestroy first.

Preferred Approach

For modern code, prefer the JSR-250 annotations @PostConstruct and @PreDestroy. They are concise, framework-neutral, and clearly express intent without coupling to Spring interfaces.

A Caveat on Prototype Destruction

The container does not call destruction callbacks for prototype beans — it hands them off and forgets them. If a prototype holds resources, you are responsible for releasing them yourself.

Graceful Shutdown

Spring Boot triggers destruction callbacks during a clean shutdown (for example on SIGTERM). Combined with graceful shutdown settings, this lets in-flight work finish and resources close cleanly before exit.

server:
  shutdown: graceful
spring:
  lifecycle:
    timeout-per-shutdown-phase: 20s

Quick Check

Test your understanding of lifecycle callbacks.

Recap

Lifecycle callbacks manage setup and cleanup.

  • @PostConstruct runs after dependencies are injected
  • @PreDestroy runs before shutdown for cleanup
  • InitializingBean/DisposableBean work but couple to Spring
  • Use initMethod/destroyMethod for @Bean-created types
  • Prototype destruction is your responsibility

자주 묻는 질문

“수명 주기 콜백” 강의는 무료인가요?

네 — “수명 주기 콜백” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Spring Boot 4 Microservices & REST APIs 강의 전체를 잠금 해제할 수 있습니다. Spring Boot 4 Microservices & REST APIs 강의에는 총 4개의 강의가 포함되어 있습니다.

“수명 주기 콜백”에서 뭘 배우나요?

빈 초기화 및 소멸 단계에 연결해 보세요. 브라우저에서 직접 실행하는 실습 코드로 Spring Boot 4 Microservices & REST APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Spring Boot 4 Microservices & REST APIs을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Spring Boot 4 Microservices & REST APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 4번째 강의입니다.

“수명 주기 콜백” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Spring Boot 4 Microservices & REST APIs 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Spring Boot 4 Microservices & REST APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Spring IoC 컨테이너
  2. 생성자 주입과 필드 주입
  3. 빈 범위
  4. 수명 주기 콜백
← Spring Boot 4 Microservices & REST APIs(으)로 돌아가기