How the container builds a bean
Think of a restaurant kitchen before opening. The chef doesn’t cook each dish from scratch when the first guest arrives: the stations are set up in a fixed order, ingredients are delivered to the right station, every station checks its equipment, and only then are the doors opened.
Spring does the same with your beans when the application starts:
- Read the plan. It finds every bean definition (scanned
@Componentclasses,@Beanmethods, auto-configuration). - Create each bean by calling its constructor, passing the beans it depends on.
- Initialize it: methods marked
@PostConstructrun now, when every dependency is already there. - Wrap it if needed: for
@Transactional,@Cacheableor@Async, Spring puts a proxy around the bean, and the proxy is what other beans receive. - Use it for the whole life of the application.
- Clean up on shutdown: methods marked
@PreDestroyrun, so connections and files are closed.
The container works in two phases. First it collects bean definitions (metadata: class, scope, dependencies, factory method), and runs BeanFactoryPostProcessors, which may change definitions before any bean exists (property placeholder resolution, @Configuration class processing and auto-configuration conditions work at this level). Then it instantiates singletons in dependency order: constructor, field and setter injection, *Aware callbacks, BeanPostProcessor.postProcessBeforeInitialization (where @PostConstruct is invoked by a high-priority processor), InitializingBean.afterPropertiesSet, custom init methods, and finally postProcessAfterInitialization, where the auto-proxy creator replaces the bean with an AOP proxy if any advice applies. Destruction runs in reverse dependency order: @PreDestroy, DisposableBean.destroy, destroy methods, but only for beans whose lifecycle the container owns (not prototypes).
Interview follow-ups live at the edges: why a bean must not call its own proxied methods during initialization, why circular dependencies are rejected by default since Spring Boot 2.6, and where to start work that needs a fully started application (SmartLifecycle, ApplicationReadyEvent). The Detailed version covers them.
@Component
class PriceFeed(private val client: FeedClient) { // 1. created, dependencies passed in
private lateinit var subscription: Subscription
@PostConstruct
fun connect() { // 2. initialized: client is ready to use
subscription = client.subscribe("EUR/USD")
}
@PreDestroy
fun disconnect() { // 3. on shutdown: release the resource
subscription.cancel()
}
}@Component
public class PriceFeed {
private final FeedClient client;
private Subscription subscription;
public PriceFeed(FeedClient client) { // 1. created, dependencies passed in
this.client = client;
}
@PostConstruct
void connect() { // 2. initialized: client is ready to use
subscription = client.subscribe("EUR/USD");
}
@PreDestroy
void disconnect() { // 3. on shutdown: release the resource
subscription.cancel();
}
}Why not open the subscription in the constructor? You could, since constructor injection already gives you client. But @PostConstruct makes the order explicit, keeps the constructor fast and simple (easy to test), and pairs naturally with @PreDestroy. The rule that matters most: anything you open, close in @PreDestroy, or every restart in tests and every redeploy leaks connections.
Predict the output
A bean prints a line in its constructor, in an @Autowired setter, in a @PostConstruct method and in afterPropertiesSet() (it implements InitializingBean). In which order do the lines appear?
@Component
class Probe : InitializingBean {
init { println("constructor") }
@Autowired
fun setClock(clock: Clock) { println("setter") }
@PostConstruct
fun init() { println("@PostConstruct") }
override fun afterPropertiesSet() { println("afterPropertiesSet") }
}@Component
class Probe implements InitializingBean {
Probe() { System.out.println("constructor"); }
@Autowired
void setClock(Clock clock) { System.out.println("setter"); }
@PostConstruct
void init() { System.out.println("@PostConstruct"); }
@Override
public void afterPropertiesSet() { System.out.println("afterPropertiesSet"); }
}The object must exist before anything can be injected into it, and injection must be complete before initialization: constructor, then setter injection, then the initialization callbacks. Among those, @PostConstruct runs first (a post-processor calls it), then afterPropertiesSet(), then any custom init method. Most code only needs constructor injection and, sometimes, @PostConstruct.
Starting work too early
Tap the line with the bug.
@Component
class OrderListener(
private val queue: OrderQueue,
private val orders: OrderService,
) {
init {
Thread { queue.consume(orders::handle) }.start()
}
}@Component
public class OrderListener {
private final OrderQueue queue;
private final OrderService orders;
public OrderListener(OrderQueue queue, OrderService orders) {
this.queue = queue;
this.orders = orders;
new Thread(() -> queue.consume(orders::handle)).start();
}
}Hint: When does this thread start, compared with the rest of the application? And what stops it?
The thread starts in the constructor, while Spring is still creating other beans. Messages may be handled before the database migrations ran, before caches are warm, before orders is wrapped in its transactional proxy. If startup fails later, the thread keeps running in a half-started app. And nothing stops it on shutdown.
Start background work when the application is ready, and stop it on shutdown:
@Component
class OrderListener(
private val queue: OrderQueue,
private val orders: OrderService,
) {
@EventListener(ApplicationReadyEvent::class)
fun start() = queue.consume(orders::handle)
@PreDestroy
fun stop() = queue.close()
}@Component
public class OrderListener {
private final OrderQueue queue;
private final OrderService orders;
public OrderListener(OrderQueue queue, OrderService orders) {
this.queue = queue;
this.orders = orders;
}
@EventListener(ApplicationReadyEvent.class)
void start() { queue.consume(orders::handle); }
@PreDestroy
void stop() { queue.close(); }
}Libraries like Spring Kafka already do this for you: listener containers implement SmartLifecycle, start after all singletons exist and stop before they’re destroyed.
Circular dependencies
If A needs B in its constructor and B needs A, there’s no order in which both can be created. With field injection, older Spring versions resolved cycles by injecting an early, not yet initialized reference, which hid design problems and broke when proxies were involved (B got the raw A, not its transactional proxy). Since Spring Boot 2.6, circular references are prohibited by default and startup fails with a description of the cycle. spring.main.allow-circular-references=true brings back the old behavior, but the fix is structural: extract the shared logic into a third bean, publish an event instead of calling back, or, as a last resort, inject ObjectProvider<A> and resolve lazily.
Extension points worth knowing
BeanFactoryPostProcessorchanges bean definitions before any bean is created (register beans programmatically, rewrite properties). It must not request beans itself, or they’re created too early and miss post-processing.BeanPostProcessorsees each bean instance after creation and can return a different object, which is how proxies replace beans. A bean that a post-processor depends on is created before the post-processors are registered and logs “is not eligible for getting processed by all BeanPostProcessors”: it won’t get its@Transactionalproxy.SmartLifecycle(with a phase) starts components after all singletons exist and stops them in reverse order on shutdown; graceful shutdown (server.shutdown=graceful) uses the same phases to drain requests.- Lazy initialization (
spring.main.lazy-initialization=true,@Lazy) speeds up startup but moves configuration errors from startup to the first request.
Deep diveWhy a BeanFactoryPostProcessor @Bean method should be staticInterview favorite
@Bean methods live on a @Configuration class, which is itself a bean. To call a non-static @Bean method, Spring must create the configuration class first. For a BeanFactoryPostProcessor, that’s a problem: post-processors run before ordinary beans are created, so creating the configuration class this early means it (and anything it injects) misses later processing, like @Autowired fields and @Value resolution.
Declaring the method static lets Spring call it without an instance of the configuration class. That’s why PropertySourcesPlaceholderConfigurer beans are traditionally declared with static @Bean, and why Spring logs a warning when a non-static @Bean method returns a BeanFactoryPostProcessor.
- Two phases: bean definitions (changed by
BeanFactoryPostProcessors, conditions evaluated) then instances: constructor, injection,*Aware,@PostConstruct/afterPropertiesSet/ init method, thenpostProcessAfterInitialization, where AOP proxies replace beans. - Shutdown in reverse dependency order:
@PreDestroy,destroy(); never for prototypes. - Start background work on
ApplicationReadyEventor withSmartLifecycle, not in constructors. Circular references fail by default since Boot 2.6: fix the design.
Check this part
Where should a bean open a connection that needs its injected dependencies?
A bean starts a background thread in its constructor. What's the problem?
At which point does a @Transactional bean get replaced by its proxy?
Bean A injects B in its constructor and B injects A. What happens in a current Spring Boot app?