Bean Scopes & Lifecycle — Java Interview Guide | Cracked Java
Mid

Bean Scopes & Lifecycle

The bean scopes, the full instantiation-to-ready lifecycle order, @PostConstruct/@PreDestroy, injecting prototypes into singletons, and Bean(Factory)PostProcessor.

Prereqs: ioc-di-applicationcontext

A Spring bean has two orthogonal properties the container manages for you: its scope (how many instances exist and how long each lives) and its lifecycle (the ordered sequence of callbacks the container drives from raw object to fully-wired, ready-to-use bean). Mastering both is what separates "I annotate things and they work" from "I know exactly when my code runs and why."

Scope answers how many and how long. The default is singleton — one shared instance per container, created eagerly at startup and cached for the application's life. prototype gives a brand-new instance on every lookup and the container stops tracking it after creation. The web scopes (request, session, application, websocket) tie an instance's life to an HTTP request, an HTTP session, the ServletContext, or a WebSocket session respectively.

@Component
@Scope("prototype")          // new instance per getBean / injection point
public class ReportBuilder { }

@Component                     // implicit singleton
public class ReportService { }

Lifecycle answers what runs and in what order. After Spring instantiates a bean and injects its dependencies, it fires a fixed chain: Aware callbacks → BeanPostProcessor before-init → @PostConstructInitializingBean.afterPropertiesSet() → custom init-methodBeanPostProcessor after-init → ready. On shutdown it reverses to @PreDestroyDisposableBean.destroy() → custom destroy-method. Those BeanPostProcessor hooks are not academic — they're how @Autowired, @Transactional, and AOP proxies get woven in.

The two extension points people confuse are BeanFactoryPostProcessor (rewrites bean definitions before any bean is instantiated — e.g. PropertySourcesPlaceholderConfigurer resolving ${...}) and BeanPostProcessor (touches instances after instantiation). Knowing which operates on definitions vs instances is a frequent senior probe.

The questions below cover each scope, the exact lifecycle order, @PostConstruct/@PreDestroy, the prototype-in-singleton pitfall, both post-processor types, and how to choose between interfaces, annotations, and XML.

Questions

7 in this topic