Retornos de chamada do ciclo de vida
Conecte-se às fases de inicialização e destruição dos beans.
Retornos de chamada do ciclo de vida é uma aula grátis de Spring Boot 4 Microservices & REST APIs no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Spring Boot 4 Microservices & REST APIs, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Spring Boot 4 Microservices & REST APIs inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em 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
Perguntas Frequentes
A aula “Retornos de chamada do ciclo de vida” é grátis?
Sim — o texto completo de “Retornos de chamada do ciclo de vida” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Spring Boot 4 Microservices & REST APIs, atualize para CoddyKit PRO. O curso de Spring Boot 4 Microservices & REST APIs inclui 4 aulas no total.
O que vou aprender em “Retornos de chamada do ciclo de vida”?
Conecte-se às fases de inicialização e destruição dos beans. Você pratica Spring Boot 4 Microservices & REST APIs com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Spring Boot 4 Microservices & REST APIs?
Nenhuma experiência prévia é necessária. Spring Boot 4 Microservices & REST APIs no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Retornos de chamada do ciclo de vida”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Spring Boot 4 Microservices & REST APIs?
Sim. Cada aula de Spring Boot 4 Microservices & REST APIs inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- O contêiner de IoC do Spring
- Injeção por construtor versus por campo
- Escopos de beans
- Retornos de chamada do ciclo de vida