Callbacks del ciclo de vida
Conéctese a las fases de inicialización y destrucción de los beans
Callbacks del ciclo de vida es una lección gratuita de Spring Boot 4 Microservices & REST APIs en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Spring Boot 4 Microservices & REST APIs, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Spring Boot 4 Microservices & REST APIs incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
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: 20sQuick Check
Test your understanding of lifecycle callbacks.
Recap
Lifecycle callbacks manage setup and cleanup.
@PostConstructruns after dependencies are injected@PreDestroyruns before shutdown for cleanupInitializingBean/DisposableBeanwork but couple to Spring- Use
initMethod/destroyMethodfor@Bean-created types - Prototype destruction is your responsibility
Preguntas frecuentes
¿La lección «Callbacks del ciclo de vida» es gratis?
Sí — el texto completo de «Callbacks del ciclo de vida» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Spring Boot 4 Microservices & REST APIs, actualiza a CoddyKit PRO. El curso de Spring Boot 4 Microservices & REST APIs incluye 4 lecciones en total.
¿Qué aprenderé en «Callbacks del ciclo de vida»?
Conéctese a las fases de inicialización y destrucción de los beans Practicas Spring Boot 4 Microservices & REST APIs con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Spring Boot 4 Microservices & REST APIs?
No se requiere experiencia previa. Spring Boot 4 Microservices & REST APIs en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Callbacks del ciclo de vida»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Spring Boot 4 Microservices & REST APIs?
Sí. Cada lección de Spring Boot 4 Microservices & REST APIs incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- El contenedor IoC de Spring
- Inyección por constructor frente a inyección por campos
- Ámbitos de los beans
- Callbacks del ciclo de vida