Bean Scopes and Lifecycle

Introduction

Welcome to this lesson on Bean Scopes and Lifecycle! So far, we've covered what Spring and Spring Boot are, delved into the project structure, and understood the importance of files like application.properties. We've also explored concepts such as Inversion of Control (IoC) and Dependency Injection (DI). We learned how to create simple beans without dependencies and, in the previous lesson, learned to create beans with dependencies. This lesson will explore the concepts of bean scopes and bean lifecycle, which are crucial for managing the state and lifecycle of beans in a Spring application.

Understanding Bean Scopes

In Spring, all beans are by default singletons, meaning only one instance of each bean exists in the application context. This single instance is reused wherever the bean is injected, making it efficient for stateless beans that can be used multiple times across the application without side effects. By ensuring that there is only one instance, Spring makes it possible to wire beans by type, as there won't be any ambiguity.

However, not all beans should be singletons. In scenarios where a class maintains some state and hence isn't safe for reuse, a different scope might be needed. Here are the main bean scopes in Spring:

  • Singleton: One instance of the bean is created for the entire application.
  • Prototype: A new instance is created each time the bean is requested.
  • Session: In a web application, one instance is created for each session.
  • Request: In a web application, one instance is created for each HTTP request.

You can declare a different scope using the @Scope annotation alongside the @Component or @Bean annotation.

Declaring a Prototype Bean with @Component

To define a prototype-scoped bean using the @Component annotation, you need to utilize the @Scope annotation. Here's how you can do it:

Kotlin
package com.example

import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Component

@Component
@Scope("prototype")
class PrototypeComponentBean {
    init {
        println("PrototypeComponentBean instance created.")
    }
}

In this example, each time a PrototypeComponentBean is requested from the application context, a new instance is created. This approach is particularly useful for stateful beans that should not share the state with other instances.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal