Sub topic 1
The Container and What It Manages
Prerequisites
You should know core Java interfaces and annotations. You should also understand basic Spring dependency injection with @Component, @Bean, and constructor injection. The examples assume you can build and run a Spring application.
The Container and What It Manages
The Spring IoC container creates and manages objects called beans. IoC, or inversion of control, means your application does not decide when to construct every dependency. The container does that work from configuration.
An ApplicationContext is the container most applications use. It stores bean definitions, creates bean instances, connects their dependencies, applies framework processing, and later destroys managed beans.
From Bean Definition to Bean Instance
A bean definition is metadata that tells Spring how to create a bean. It can include the class, scope, dependencies, and lifecycle methods.
Spring finds definitions from component scanning, configuration classes, and @Bean methods. The definition is a recipe, not the object itself. Spring can use one recipe to create a singleton instance, or use it repeatedly for another scope.
Instantiation and Dependency Injection
Instantiation means calling a constructor to create the object. Spring chooses a constructor whose dependencies it can provide. Constructor injection makes those required dependencies explicit.
After construction, Spring resolves and supplies the dependencies. It then invokes relevant callbacks and applies bean processors. A bean processor is a Spring extension that can inspect or replace beans during creation.
@Component
class OrderService {
private final PaymentClient paymentClient;
OrderService(PaymentClient paymentClient) {
this.paymentClient = paymentClient;
}
}The Phases of a Bean's Life
A typical managed bean moves through these phases:
- Spring reads its definition.
- Spring constructs the object.
- Spring injects dependencies.
- Aware callbacks and pre-initialization processors run.
- Initialization callbacks run.
- The bean is ready for application code.
- When the context closes, destruction callbacks run.
The exact callbacks depend on the bean and its configuration. Prototype beans, for example, do not receive container-managed destruction callbacks.
Initialization Callbacks
Common initialization hooks include @PostConstruct, InitializingBean.afterPropertiesSet(), and a method named by @Bean(initMethod = "..."). They run after dependency injection. In normal processing, @PostConstruct runs before afterPropertiesSet, followed by the configured custom init method.
Use annotation callbacks for application code. Use InitializingBean when implementing a Spring-specific component. Use a named method when configuring a class you cannot modify.
Exercise
What does a bean definition represent?
Show answer
It is metadata, or a recipe, that tells Spring how to create and manage a bean.