0Pricing
Spring Boot 4 Microservices & REST APIs · Lezione

Callback del ciclo di vita

Si colleghi alle fasi di inizializzazione e distruzione dei bean.

Callback del ciclo di vita è una lezione Spring Boot 4 Microservices & REST APIs gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Spring Boot 4 Microservices & REST APIs, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Spring Boot 4 Microservices & REST APIs include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

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

Domande Frequenti

La lezione «Callback del ciclo di vita» è gratuita?

Sì — il testo completo di «Callback del ciclo di vita» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Spring Boot 4 Microservices & REST APIs, passa a CoddyKit PRO. Il corso Spring Boot 4 Microservices & REST APIs include 4 lezioni in totale.

Cosa imparerò in «Callback del ciclo di vita»?

Si colleghi alle fasi di inizializzazione e distruzione dei bean. Eserciti Spring Boot 4 Microservices & REST APIs con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Spring Boot 4 Microservices & REST APIs?

Non è richiesta alcuna esperienza precedente. Spring Boot 4 Microservices & REST APIs su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.

Quanto tempo richiede la lezione «Callback del ciclo di vita»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Spring Boot 4 Microservices & REST APIs?

Sì. Ogni lezione Spring Boot 4 Microservices & REST APIs include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Il container IoC di Spring
  2. Injection tramite costruttore o campo
  3. Scope dei bean
  4. Callback del ciclo di vita
← Torna a Spring Boot 4 Microservices & REST APIs