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.