Video in progress
When are @PostConstruct and @PreDestroy called?
@PostConstruct runs once, after the bean has been created and all dependencies are injected. @PreDestroy runs when the context is closing, before the bean goes away (it's never called for prototype beans).
📖 Answer
A short version of the bean lifecycle:
- constructor;
- setter/field injection;
Awareinterfaces, the "before" part ofBeanPostProcessor;@PostConstruct;afterPropertiesSet(),initMethod;- the proxy is created (
@Transactionaland so on) — the "after" part; - ... the application runs ...
@PreDestroy,destroy().
@Component
public class RatesCache {
@PostConstruct
void load() { refresh(); } // dependencies are ready, safe to use
@PreDestroy
void close() { executor.shutdown(); }
}
Watch out:
@Transactionaldoesn't work inside@PostConstruct— the proxy isn't ready yet. If you need to write to the database, do it onApplicationReadyEvent.- Long work (say, a 2-minute load) slows down startup, and health checks start failing.
- In Boot 3 the annotations come from the
jakarta.annotationpackage.
Sign up to mark studied questions and save your progress.