Bean Scopes

Back

Loading concept...

Bean Scopes in Jakarta EE: The Magical Backpacks Story 🎒

Imagine you’re at a magical school where everyone carries special backpacks. These backpacks hold your stuff (data), but here’s the twist: different backpacks last for different amounts of time!

In Jakarta EE, we call these backpacks Bean Scopes. They control how long your objects live and who can share them.


🎯 What Are Bean Scopes?

Think of it this way:

A bean = A helper object that does work for you A scope = How long that helper sticks around

Simple Example:

  • A notepad you use for one math problem → disappears when you’re done
  • A lunchbox you carry all day → stays until school ends
  • The school clock on the wall → everyone sees the same one, forever

Bean scopes work exactly like this!


🗺️ The Five Magical Scopes

graph LR A["Bean Scopes"] --> B["Request Scope"] A --> C["Session Scope"] A --> D["Application Scope"] A --> E["Conversation Scope"] A --> F["Dependent Scope"] B --> B1["⏱️ Lives for ONE request"] C --> C1["📚 Lives for user's visit"] D --> D1["🏫 Lives forever for everyone"] E --> E1["💬 Lives during a chat"] F --> F1["👤 Lives with its parent"]

Let’s explore each one!


1️⃣ Request Scope: The Sticky Note 📝

What Is It?

A Request Scope bean lives for just ONE request. When you ask the server something, it creates the bean. When the answer comes back, the bean disappears!

Real Life Analogy

Imagine writing on a sticky note during class:

  • You write a question ✍️
  • Teacher answers ✅
  • You throw away the sticky note 🗑️

Each question = new sticky note!

When To Use It?

Use Request Scope when you need data for just one action:

  • Processing a form submission
  • Calculating something for one page
  • Handling a single button click

Code Example

@RequestScoped
public class ShoppingCartHelper {

    private double currentTotal;

    public void calculateTotal(
        List<Item> items
    ) {
        this.currentTotal = items
            .stream()
            .mapToDouble(Item::getPrice)
            .sum();
    }

    public double getTotal() {
        return currentTotal;
    }
}

What happens:

  1. User clicks “Calculate” → Bean is born
  2. Calculation runs → Bean does its job
  3. Response sent → Bean disappears forever

2️⃣ Session Scope: Your Personal Locker 🔐

What Is It?

A Session Scope bean lives for your entire visit to the website. It remembers you from page to page!

Real Life Analogy

Think of your school locker:

  • You arrive at school → Locker is assigned to you
  • All day, you put stuff in and take stuff out
  • You go home → Locker is cleaned out for tomorrow

Your locker = Your session. Nobody else can use YOUR locker!

When To Use It?

Use Session Scope for data that should follow a user:

  • Shopping cart contents
  • User preferences
  • Login status

Code Example

@SessionScoped
public class UserCart implements
    Serializable {

    private List<Product> items =
        new ArrayList<>();

    public void addItem(Product p) {
        items.add(p);
    }

    public List<Product> getItems() {
        return items;
    }

    public void clear() {
        items.clear();
    }
}

What happens:

  1. User logs in → Cart bean is created
  2. User browses 10 pages → Same cart follows them
  3. User closes browser → Cart disappears

3️⃣ Application Scope: The School Clock 🕐

What Is It?

An Application Scope bean lives as long as the app runs. Everyone in the entire school shares the SAME one!

Real Life Analogy

Think of the big clock in the school hallway:

  • There’s only ONE clock
  • ALL students see the SAME time
  • It never disappears (until the school closes)

When To Use It?

Use Application Scope for shared, global data:

  • Configuration settings
  • Cache that everyone uses
  • Counter of total website visitors

Code Example

@ApplicationScoped
public class AppConfig {

    private String appVersion = "2.0";
    private int totalVisitors = 0;

    public String getVersion() {
        return appVersion;
    }

    public synchronized int
        incrementVisitors() {
        return ++totalVisitors;
    }

    public int getTotalVisitors() {
        return totalVisitors;
    }
}

What happens:

  1. Server starts → ONE AppConfig is created
  2. User A asks for version → Gets “2.0”
  3. User B asks for version → Gets SAME “2.0”
  4. Server stops → Bean finally disappears

⚠️ Warning: Since everyone shares it, be careful with changes!


4️⃣ Conversation Scope: The Group Project Chat 💬

What Is It?

A Conversation Scope bean lives for a multi-step conversation. It’s longer than one request, but shorter than a full session.

Real Life Analogy

Imagine a group project chat:

  • You start discussing homework 📱
  • Chat continues for 20 messages 💬
  • Project is done → Chat ends ✅

The chat isn’t forever (like your school), but it’s more than one message!

When To Use It?

Use Conversation Scope for multi-step processes:

  • Wizard forms (Step 1, Step 2, Step 3…)
  • Checkout process
  • Booking flows

Code Example

@ConversationScoped
public class BookingWizard implements
    Serializable {

    @Inject
    private Conversation conversation;

    private String flight;
    private String seat;
    private String meal;

    public void startBooking() {
        conversation.begin();
    }

    public void selectFlight(String f) {
        this.flight = f;
    }

    public void selectSeat(String s) {
        this.seat = s;
    }

    public void complete() {
        // Save booking
        conversation.end();
    }
}

What happens:

  1. User clicks “Book Now” → conversation.begin()
  2. User picks flight → Data saved in bean
  3. User picks seat → Same bean remembers flight
  4. User confirms → conversation.end(), bean gone

5️⃣ Dependent Scope: The Shadow Friend 👥

What Is It?

A Dependent Scope bean has no life of its own. It lives and dies with whatever bean uses it!

Real Life Analogy

Think of your shadow:

  • When you appear, your shadow appears
  • Your shadow goes wherever YOU go
  • When you leave, your shadow leaves too

The shadow doesn’t decide anything. It just follows!

When To Use It?

Dependent is the default scope. Use it when:

  • The bean is a simple helper
  • It doesn’t need to be shared
  • It should be created fresh each time

Code Example

@Dependent
public class PriceCalculator {

    public double applyDiscount(
        double price,
        int percent
    ) {
        return price *
            (1 - percent / 100.0);
    }
}

@SessionScoped
public class ShoppingCart {

    @Inject
    private PriceCalculator calc;

    // calc lives as long as
    // ShoppingCart lives
}

What happens:

  1. ShoppingCart is created → PriceCalculator is born
  2. ShoppingCart is used → Same PriceCalculator
  3. ShoppingCart dies → PriceCalculator dies too

🎨 Quick Comparison

Scope Lives For Shared By Analogy
Request 1 request Nobody Sticky note
Session User visit Same user Locker
Application Forever Everyone School clock
Conversation Multi-step Same user Group chat
Dependent Parent’s life Parent only Shadow

🧠 How To Choose?

Ask yourself these questions:

graph TD Q1["Does EVERYONE&lt;br&gt;need the same data?"] Q1 -->|Yes| APP["Application Scope"] Q1 -->|No| Q2 Q2["Does data need to&lt;br&gt;survive across pages?"] Q2 -->|No| REQ["Request Scope"] Q2 -->|Yes| Q3 Q3["Is it a multi-step&lt;br&gt;wizard or process?"] Q3 -->|Yes| CONV["Conversation Scope"] Q3 -->|No| SESS["Session Scope"] Q4["Is it a simple&lt;br&gt;helper with no state?"] Q4 -->|Yes| DEP["Dependent Scope"]

🎯 Golden Rules

  1. Start Small → Use @RequestScoped unless you need more
  2. Share Carefully@ApplicationScoped = everyone sees changes
  3. Sessions Are Personal → Each user has their own session data
  4. Conversations Have Limits → Don’t forget to call end()!
  5. Dependent = Default → If you don’t specify, you get this

🚀 You’ve Got This!

Bean scopes are just about timing and sharing:

  • How long does my data need to live?
  • Who needs to see it?

Pick the right scope, and your app will run smoothly!

Remember the magical school:

  • 📝 Sticky notes for quick tasks
  • 🔐 Lockers for personal stuff
  • 🕐 School clock for everyone
  • 💬 Group chats for projects
  • 👥 Shadows that follow their owner

Now go build something amazing! 🎉

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.