1.3 Spring Container & Bean
Let's explore how Spring manages and assembles objects, focusing on the Spring Container and its managed objects, Beans.
1. Spring Container
The Spring Container is like a giant warehouse responsible for the creation, dependency injection, and lifecycle management of Java objects. Instead of developers manually creating objects using the new operator, the container takes over that responsibility.
- Core Interfaces:
BeanFactory(root interface),ApplicationContext(the most widely used container with extra features) - Role: It creates objects and connects them based on configuration information (Java Config, annotations, etc.).
2. Spring Bean
A Java object managed by the Spring Container is called a 'Bean'. Not all objects are beans; only those explicitly registered for management by Spring become beans.
Ways to Register Beans
- Annotation-based (Component Scan): By adding
@Componentto a class, Spring automatically finds and registers it as a bean.@Controller,@Service,@Repository, etc., are all specialized annotations that include@Component.
- Direct Registration (Java Config): By using
@Beanon a method within a@Configurationclass, the returned value is explicitly registered as a bean.
3. Bean Lifecycle
A bean is created when the Spring Container starts and is managed until the container shuts down.
- Spring Container Creation
- Spring Bean Creation
- Dependency Injection
- Initialization Callback: The bean is ready for use.
- Usage: Executing application logic.
- Destruction Callback: Finalizing tasks like resource cleanup.
- Spring Shutdown
4. Bean Scope
By default, Spring beans are managed as Singletons. This means only one instance is created per container and shared everywhere.
- Singleton (Default): Only one instance per Spring Container.
- Prototype: A new instance is created every time the bean is requested.
In practice, the Singleton mode is mostly used to optimize memory usage and ensure that Spring can safely manage the state of objects.