Spring Bean
What Is a Spring Bean?
- An independent object managed by the Spring Framework.
- It is an ordinary Java object, except that Spring manages it.
- Simply put, it is an object that performs a task and can be used for DI at any time while Spring manages it.
Spring Container: Also Called an IoC, Bean, or DI Container
What Is a Container?
- A container generally manages the life cycle of instances and provides additional features to created instances.
- In other words, it references application code and controls object creation and destruction.
Spring Container
- Manages Spring Bean objects.
- Creates and uses Bean objects based on developer-defined Bean classes.
- The container, rather than the developer, creates objects. This enables DI and lets the Spring container control them.
What Is IoC (Inversion of Control)?
- It is called inversion of control because the container controls the program flow previously controlled by the developer.
- Spring IoC manages object creation and life cycles. Transferring control to the Spring Framework enables DI and AOP.
Five Spring Bean Scopes
- singleton
- Only one object exists in the Spring IoC container for a Bean definition.
- This is the default scope when none is specified.
- prototype
- Multiple objects can exist for one Bean definition.
- A new object is created for every request.
- A new prototype Bean is created when injected into a dependent Bean.
- It is removed normally by garbage collection.
- request
- One object exists for one HTTP request life cycle.
- Each HTTP request has its own object.
- Valid only in a web-aware Spring
ApplicationContext.
- session
- One object exists for one HTTP session life cycle.
- Valid only in a web-aware Spring
ApplicationContext.
- global session
- One object exists for one global HTTP session life cycle.
- Generally valid in a portlet context.
- Valid only in a web-aware Spring
ApplicationContext.
Creating Spring Beans with Java Annotations
@Bean
- Use it to register a class from an external library as a Spring Bean.
- Use
@Beanfor external libraries that you cannot directly control. - Declare it inside a class annotated with
@Configuration. - The object returned by a developer-written method becomes a Bean.
- Use
@Component
- Use it to register a developer-written class as a Spring Bean.
- A developer-written class becomes a Bean.
Use the following annotations when the class has a specific role:
@Controller- Fundamentally the same as
@Component. - Emphasizes a presentation-layer component.
- Fundamentally the same as
@Service- Fundamentally the same as
@Component. - Emphasizes a business-layer component that implements business logic.
- Fundamentally the same as
@Repository- Fundamentally the same as
@Component. - Emphasizes a persistence-layer component, such as database access.
- Catches platform-specific exceptions and throws Spring unchecked exceptions.
- Fundamentally the same as