Lifecycle Callbacks
Hook into bean init and destroy phases.
Lifecycle Callbacks is a free Spring Boot 4 Microservices & REST APIs lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Spring Boot 4 Microservices & REST APIs learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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
Frequently asked questions
Is the “Lifecycle Callbacks” lesson free?
Yes — the full text of “Lifecycle Callbacks” is free to read here on the web, and the Spring Boot 4 Microservices & REST APIs course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Spring Boot 4 Microservices & REST APIs course, upgrade to CoddyKit PRO.
What will I learn in “Lifecycle Callbacks”?
Hook into bean init and destroy phases. You practise Spring Boot 4 Microservices & REST APIs with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Spring Boot 4 Microservices & REST APIs?
No prior experience is required. Spring Boot 4 Microservices & REST APIs on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Lifecycle Callbacks” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Spring Boot 4 Microservices & REST APIs lesson?
Yes. Every Spring Boot 4 Microservices & REST APIs lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- The Spring IoC Container
- Constructor vs Field Injection
- Bean Scopes
- Lifecycle Callbacks