Bean Scopes in Spring Framework: The Lifespans of Your Beans! 🫘

Akshay Gengaje - Sep 12 - - Dev Community

Welcome to the world of Spring beans, where beans are more than just something you eat for dinner 🍲. In Spring, beans are the objects that form the backbone of your application, and the scope of these beans determines their lifecycle: when they're created, how long they live, and when they’re destroyed.

Think of bean scopes as different lifestyles for your beans. Some beans are chill and live forever, while others pop in and out as needed—like special guests at a party! 🎉

Let’s explore the various scopes, how they work, and where you might want to use them.


What is a Bean in Spring? 🫘

Before we dive into scopes, let’s quickly recap what a bean is. In the Spring Framework, a bean is simply an object that is managed by the Spring IoC container. When Spring starts up, it creates beans for you, injects dependencies, and manages their lifecycle. The scope of a bean determines how long it stays around.


Types of Bean Scopes in Spring: The Different Lifestyles 🌱

Spring provides several different bean scopes, each serving a different purpose. These bean scopes are like different ways of managing the objects in your Spring container.

Let’s break down the main scopes and when to use each:

  1. Singleton (The Forever Bean 🏰)
  2. Prototype (The Bean with Multiple Lives 🎭)
  3. Request (The Bean for Each HTTP Request 📩)
  4. Session (The Bean for User Sessions 🧳)
  5. Global Session (For Portlet Applications 🌍)

1. Singleton Scope: The Forever Bean 🏰

Singleton is the default scope in Spring, which means unless you specify otherwise, your beans are singletons. In this scope, only one instance of the bean is created for the entire Spring container, and that instance is shared across the whole application.

So, think of it like a king in a castle. There’s only one king, and everyone in the kingdom shares that same king! 👑

When to Use Singleton?

  • Use it when you want to share a single instance across your entire application.
  • It's perfect for stateless services, like a service that talks to a database.

Example:

@Service
public class CastleService {
    public void defend() {
        System.out.println("The castle is defended by the Singleton King! 🏰🛡️");
    }
}
Enter fullscreen mode Exit fullscreen mode

How to Define It?

You don’t need to do anything special, as singleton is the default scope. But for fun, you can define it explicitly:

@Bean
@Scope("singleton")
public CastleService castleService() {
    return new CastleService();
}
Enter fullscreen mode Exit fullscreen mode

2. Prototype Scope: The Bean with Multiple Lives 🎭

While the singleton bean lives forever, the prototype bean has multiple lives! Every time you request a bean with the prototype scope, Spring creates a new instance. It’s like hiring multiple actors to play the same role in different scenes 🎬.

In prototype scope, the bean is created and handed over, but Spring doesn’t manage it afterward. It’s like saying, “Here’s your bean—good luck!” 🍀

When to Use Prototype?

  • Use this when you need a new instance each time the bean is requested.
  • It’s great for stateful objects, like creating a new user form for every request.

Example:

@Component
@Scope("prototype")
public class Actor {
    public void act() {
        System.out.println("A new actor is performing! 🎭");
    }
}
Enter fullscreen mode Exit fullscreen mode

How to Define It?

@Bean
@Scope("prototype")
public Actor actor() {
    return new Actor();
}
Enter fullscreen mode Exit fullscreen mode

Here, each time you call for Actor, Spring will give you a fresh, brand-new actor ready to perform.


3. Request Scope: The Bean for Each HTTP Request 📩

The request scope creates a new bean instance for each HTTP request. After the request is processed, the bean is discarded like a letter in a mailbox 📬. This scope is useful when you want to create a new instance of a bean for each web request.

When to Use Request Scope?

  • Perfect for web applications where you need to create a new bean per HTTP request.
  • Ideal for processing data that’s specific to individual requests.

Example:

@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class RequestBean {
    public void handleRequest() {
        System.out.println("Handling HTTP request! 📩");
    }
}
Enter fullscreen mode Exit fullscreen mode

How to Define It?

@Bean
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public RequestBean requestBean() {
    return new RequestBean();
}
Enter fullscreen mode Exit fullscreen mode

Each HTTP request will get its own RequestBean, ensuring that no data is shared between different requests.


4. Session Scope: The Bean for User Sessions 🧳

The session scope ties the bean's lifecycle to the HTTP session. A new bean is created for each user session, and it stays alive as long as the session does. Think of it like luggage 🧳 that stays with you during your entire trip, but once the trip is over, it’s gone!

When to Use Session Scope?

  • Use it when you want to store user-specific data across multiple requests during a session.
  • Common for web apps with user login and session management.

Example:

@Component
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class SessionBean {
    public void manageSession() {
        System.out.println("Session is active! 🧳");
    }
}
Enter fullscreen mode Exit fullscreen mode

How to Define It?

@Bean
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public SessionBean sessionBean() {
    return new SessionBean();
}
Enter fullscreen mode Exit fullscreen mode

Here, the SessionBean will live for the entire duration of the user's session, and each user will get their own bean.


5. Global Session Scope: For Portlet Applications 🌍

The global session scope is specific to portlet applications. It’s similar to the session scope, but in a portlet, there can be multiple sessions, and the global session scope is shared across multiple portlets. Think of it like a global storage box that’s shared between a few friends 🌍.

When to Use Global Session Scope?

  • Use this only when working with portlets, which are special web components.
  • It’s rarely used in standard web applications.

Example:

@Component
@Scope(value = WebApplicationContext.SCOPE_GLOBAL_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class GlobalSessionBean {
    public void manageGlobalSession() {
        System.out.println("Global session is active! 🌍");
    }
}
Enter fullscreen mode Exit fullscreen mode

How to Configure Bean Scopes in Spring: The Blueprint 🏗️

In Spring, you can define a bean’s scope in two ways:

  1. Using Annotations: You can use the @Scope annotation on your bean classes or methods.
  2. In XML Configuration: You can define the scope in your XML Spring configuration file.

Using Annotations:

@Component
@Scope("prototype")  // Set the desired scope here
public class MyBean {
    // Class definition
}
Enter fullscreen mode Exit fullscreen mode

Using XML Configuration:

<bean id="myBean" class="com.example.MyBean" scope="prototype"/>
Enter fullscreen mode Exit fullscreen mode

Wrapping Up: Bean Scopes in a Nutshell 🥜

So, what have we learned about bean scopes in Spring?

  1. Singleton: One bean to rule them all! 🏰 (Default scope)
  2. Prototype: Fresh beans every time! 🎭
  3. Request: New bean for each HTTP request 📩.
  4. Session: One bean per user session 🧳.
  5. Global Session: For portlet applications 🌍.

By understanding bean scopes, you can optimize your Spring applications, ensuring that your beans live exactly as long as they need to—no more, no less. Now go forth and manage your beans like a pro! 🫘✨


. . . . . . . . . .
Terabox Video Player