Lecture 27: Bean Scopes: Singleton, Prototype, Request, Session, Application

BMC201 - Web Technology

Mr. Prashant Kumar Nag

2026-03-11

Lecture 27

Bean Scopes: Singleton, Prototype, Request, Session, Application

Week 7 | Unit IV: Spring Framework Basics
BMC201 - Web Technology
Mr. Prashant Kumar Nag, Assistant Professor

Learning Objectives


  • Differentiate singleton, prototype, request, session, application
  • Select scope by use case
  • Avoid state bugs from wrong scope

Prerequisites


  • Core Java OOP concepts and interface-based design
  • Basic understanding of Servlets/JSP request flow from Unit III
  • Revision of Lecture 26 before moving into Bean Scopes: Singleton, Prototype, Request, Session, Application

Syllabus Mapping


  • Unit IV topic focus: Bean Scopes: Singleton, Prototype, Request, Session, Application
  • CO alignment: implementation understanding + architecture reasoning
  • Assessment alignment: short definitions + long implementation/design questions

Agenda


  • 5-minute recap from previous lecture
  • Concept deep dive: Bean Scopes: Singleton, Prototype, Request, Session, Application
  • Code/configuration walkthrough and output analysis
  • Debug checklist and exam-oriented summary

Introduction


Bean scope controls lifetime and sharing behavior.

Think About It


Should a shopping cart bean be global?

What Is Bean Scope?


Bean Scope defines the lifecycle and visibility of a bean instance within the Spring IoC container.

It controls:

  • How many instances of a bean are created
  • How long each instance lives
  • Where the instance can be accessed

The scope determines whether all requests share one instance or get separate instances.

Five Standard Bean Scopes


Spring provides five standard scopes:

  1. Singleton — one instance per Spring container (default)
  2. Prototype — new instance every time the bean is requested
  3. Request — one instance per HTTP request (web-aware)
  4. Session — one instance per HTTP session (web-aware)
  5. Application — one instance per ServletContext (web-aware)

The first two work everywhere; the last three require a web-aware ApplicationContext.

Singleton Scope


Singleton is the default scope in Spring.

  • One instance is created per container
  • All injection points receive the same shared instance
  • Instance is created eagerly at startup (or lazily if configured)

Best for: Stateless services, configuration beans, DAOs, utility classes

Warning: Never store mutable user-specific state in singleton beans

Singleton Scope Code


@Component
@Scope("singleton")  // or just @Component (default)
public class PricingService {
    private final BigDecimal taxRate;  // immutable config OK
    
    public BigDecimal calculatePrice(BigDecimal basePrice) {
        return basePrice.multiply(BigDecimal.ONE.add(taxRate));
    }
}

All controllers/services that autowire PricingService get the same instance.

Prototype Scope


Prototype creates a new instance every time the bean is requested.

  • Spring creates the bean but does not track its lifecycle
  • No destroy callbacks are invoked automatically
  • Each getBean() or @Autowired injection gets a fresh instance

Best for: Stateful objects, command objects, temporary data holders

Warning: Prototype beans injected into singletons remain the same instance

Prototype Scope Code


@Component
@Scope("prototype")
public class ShoppingCart {
    private List<Item> items = new ArrayList<>();
    
    public void addItem(Item item) {
        items.add(item);
    }
    
    public List<Item> getItems() {
        return Collections.unmodifiableList(items);
    }
}

Each request for ShoppingCart bean returns a new, independent instance.

Request Scope


Request scope creates one bean instance per HTTP request.

  • Bean instance is bound to the lifecycle of a single HTTP request
  • Different requests get different instances
  • Instance is destroyed when the request completes

Best for: Request-specific processing state, temporary calculation holders

Requires: Web-aware Spring ApplicationContext

Request Scope Code


@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST, 
       proxyMode = ScopedProxyMode.TARGET_CLASS)
public class RequestContext {
    private String requestId;
    private LocalDateTime timestamp;
    
    @PostConstruct
    public void init() {
        requestId = UUID.randomUUID().toString();
        timestamp = LocalDateTime.now();
    }
}

Each HTTP request gets its own RequestContext with unique ID and timestamp.

Session Scope


Session scope creates one bean instance per HTTP session.

  • Bean instance persists across multiple requests from the same user
  • Different users (sessions) get different instances
  • Instance is destroyed when the session expires or is invalidated

Best for: User shopping carts, user preferences, authentication state

Requires: Web-aware Spring ApplicationContext

Session Scope Code


@Component
@Scope(value = WebApplicationContext.SCOPE_SESSION,
       proxyMode = ScopedProxyMode.TARGET_CLASS)
public class UserCart {
    private List<Product> products = new ArrayList<>();
    private String userId;
    
    public void addProduct(Product product) {
        products.add(product);
    }
    
    public BigDecimal getTotalPrice() {
        return products.stream()
            .map(Product::getPrice)
            .reduce(BigDecimal.ZERO, BigDecimal::add);
    }
}

Each user session maintains its own cart instance with independent product list.

Application Scope


Application scope creates one bean instance per ServletContext.

  • Similar to singleton but scoped to ServletContext lifecycle
  • Shared across all servlets, filters, and listeners
  • Useful in multi-ApplicationContext scenarios (e.g., parent-child contexts)

Best for: Global application state, shared caches, application-wide configuration

Requires: Web-aware Spring ApplicationContext

Application Scope Code


@Component
@Scope(value = WebApplicationContext.SCOPE_APPLICATION,
       proxyMode = ScopedProxyMode.TARGET_CLASS)
public class VisitorCounter {
    private final AtomicLong totalVisitors = new AtomicLong(0);
    
    public long incrementAndGet() {
        return totalVisitors.incrementAndGet();
    }
    
    public long getTotalVisitors() {
        return totalVisitors.get();
    }
}

Tracks total visitor count across entire web application.

Understanding Scoped Proxies


When injecting a shorter-lived scope into a longer-lived scope, Spring creates a scoped proxy.

Problem: Singleton bean with session-scoped dependency

Solution: proxyMode = ScopedProxyMode.TARGET_CLASS

@Component
@Scope(value = WebApplicationContext.SCOPE_SESSION,
       proxyMode = ScopedProxyMode.TARGET_CLASS)
public class UserPreferences { }

The proxy delegates to the correct session-specific instance at runtime.

Choosing the Right Scope


Scope Lifetime Typical Use Cases
Singleton Container lifetime Services, DAOs, configuration
Prototype Per request Command objects, stateful processors
Request HTTP request Request metadata, temporary holders
Session User session Shopping carts, user preferences
Application ServletContext Global counters, shared caches

Default to singleton for stateless beans; use narrower scopes for user-specific state.

Common Scope Pitfalls


1. Mutable state in singleton beans

// WRONG: user-specific state in singleton
@Component
class OrderService {
    private Order currentOrder;  // shared across all users!
}

2. Prototype injected into singleton

// WRONG: singleton caches the prototype instance
@Component
class OrderProcessor {
    @Autowired ShoppingCart cart;  // same instance always
}

Solution: Use ObjectProvider<T> or scoped proxy for shorter-lived dependencies.

Scope Matrix


flowchart TD
    S1["Singleton\nOne instance per container"]
    S2["Prototype\nNew instance per request for bean"]
    S3["Request\nOne instance per HTTP request"]
    S4["Session\nOne instance per user session"]
    S5["Application\nOne instance per ServletContext"]

  • Choosing wrong scope causes stale state or unnecessary object creation
  • Stateless services typically use singleton
  • User-specific mutable state should not be singleton

Code Walkthrough


@Component
@Scope("prototype")
class TempReport {}

@Component
@Scope(value = WebApplicationContext.SCOPE_SESSION)
class UserCart {}

@Component
@Scope("singleton")
class PricingService {}

Memory Booster


Syllabus memory points for Bean Scopes: Singleton, Prototype, Request, Session, Application:

  • Core recall: scope configuration for bean instances
  • Exam compare: Singleton scope vs Prototype scope
  • Practical anchor: Create scoped beans and validate instance behavior

Live Demo


Live implementation for Bean Scopes: Singleton, Prototype, Request, Session, Application:

?? Open Demo: Lecture 27 - Bean Scopes: Singleton, Prototype, Request, Session, Application

Demo checklist: - Request same singleton bean twice and compare object identity - Request prototype bean twice and verify new instances - Simulate two users and compare session-scoped cart objects - Show one bug when mutable user data is stored in singleton

Resources & References


Structured Debug Checklist


  1. verify the primary API usage for Bean Scopes: Singleton, Prototype, Request, Session, Application is correct (imports, method names, config)
  2. check request/bean/session flow and object lifecycle assumptions
  3. inspect server logs for the first exception (not just the final symptom)
  4. reproduce one failing case and one passing case before finalizing fixes

Exam Preparation Questions: Short


  • Define Bean Scopes: Singleton, Prototype, Request, Session, Application with one practical use case.
  • Write/identify the key API or construct: scope configuration for bean instances.
  • Differentiate: Singleton scope vs Prototype scope.
  • Mention one common implementation error and correction.

Exam Preparation Questions: Long


  • Explain Bean Scopes: Singleton, Prototype, Request, Session, Application with architecture/flow and implementation steps.
  • Write a structured answer comparing two approaches used in this topic.
  • Discuss debugging strategy for this topic with likely failure points.

Practice Task


  • Implement: Create scoped beans and validate instance behavior.
  • Add console/log output to validate flow step-by-step.
  • Document one bug you encountered and the exact fix.

Checklist


Can you:

  • explain Bean Scopes: Singleton, Prototype, Request, Session, Application in your own words?
  • implement a basic example end-to-end?
  • identify and fix one common runtime issue?

Next Lecture


  • Topic: Lecture 28 - Autowiring & Annotations in Spring
  • Preparation required: revise this lecture summary and code walkthrough

Questions?

Next: Lecture 28