Video in progress

Strong Junior 🌱 Spring

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:

  1. constructor;
  2. setter/field injection;
  3. Aware interfaces, the "before" part of BeanPostProcessor;
  4. @PostConstruct;
  5. afterPropertiesSet(), initMethod;
  6. the proxy is created (@Transactional and so on) — the "after" part;
  7. ... the application runs ...
  8. @PreDestroy, destroy().
@Component
public class RatesCache {
    @PostConstruct
    void load() { refresh(); } // dependencies are ready, safe to use

    @PreDestroy
    void close() { executor.shutdown(); }
}

Watch out:

  • @Transactional doesn't work inside @PostConstruct — the proxy isn't ready yet. If you need to write to the database, do it on ApplicationReadyEvent.
  • Long work (say, a 2-minute load) slows down startup, and health checks start failing.
  • In Boot 3 the annotations come from the jakarta.annotation package.