Showing posts with label Singleton. Show all posts
Showing posts with label Singleton. Show all posts

Thursday, 2 August 2018

What are spring bean scopes

🚀 Want to Master Spring & Java Development?

Subscribe to Ram N Java for beginner-friendly coding tutorials and practical guides!

🔔 Subscribe to YouTube Channel

What Are Spring Bean Scopes in the Spring Framework?

When you define a bean in the Spring Framework, you are creating a recipe for creating instances of that class. The bean scope defines how Spring manages the lifecycle, creation, and sharing of those instances across your application. Grasping how bean scopes function is fundamental to designing robust, scalable, and memory-efficient enterprise Spring applications.

1. The Concept of Bean Scopes in Spring

A bean scope tells the Spring IoC container whether to reuse an existing instance or create a fresh one every time a component requests that bean:

  • Lifecycle Management: Dictates when a bean is created, how long it remains in memory, and when it is ready for garbage collection.
  • State Sharing vs. Isolation: Controls whether state changes made to a bean are visible across the entire application or isolated to a specific thread or user interaction.
  • Resource Optimization: Prevents unnecessary instantiation of heavyweight objects like database connection pools or service managers.

2. Core Scopes: Singleton vs. Prototype

The two foundational scopes supported in all standard Spring IoC containers are:

  • Singleton (Default): The IoC container creates exactly one shared instance of the bean per container context. Every request for the bean returns that identical cached instance. It is perfect for stateless services, repositories, and controllers.
  • Prototype: A new instance is created every time the bean is requested from the container (via injection or getBean()). It is intended for stateful objects where each consumer needs an isolated copy.

3. Web-Aware Scopes

When working inside web-aware application contexts (such as Spring MVC or Spring Boot web applications), Spring introduces specialized scopes:

  • Request: Bound to the lifecycle of a single HTTP request. Each HTTP request gets its own bean instance.
  • Session: Bound to an HTTP session lifecycle, ensuring user-specific data stays isolated between sessions.
  • Application: Scoped to the lifecycle of a ServletContext, shared across the whole web context.
  • Websocket: Scoped to a particular WebSocket session lifecycle.

4. Key Best Practices

To avoid common pitfalls when working with Spring bean scopes:

  • Keep singleton beans stateless to ensure thread safety across concurrent requests.
  • Be mindful of injecting a prototype bean into a singleton bean—since singletons are instantiated once, the prototype dependency will only be resolved once unless scoped proxies or lookup methods are used.

📺 Explore More Spring Framework Tutorials

Continue expanding your Java and Spring knowledge with these related tutorials from our channel:


Click here to watch on Youtube: 
https://www.youtube.com/watch?v=LaccwPDLF3Y&list=UUhwKlOVR041tngjerWxVccw

Click the below Image to Enlarge:
What are spring bean scopes

See also:
  • All JavaEE Videos Playlist
  • All JavaEE Videos
  • All JAVA EE Links
  • Spring Tutorial
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Cooking Tutorial
  • What are the different types of spring bean scopes

    🚀 Want to Master Spring & Java Development?

    Subscribe to Ram N Java for beginner-friendly coding tutorials and practical guides!

    🔔 Subscribe to YouTube Channel

    Understanding Spring Bean Scopes: Complete Overview

    In the Spring Framework, defining a bean does not merely create an object recipe—it also defines the lifecycle and visibility of the instances created from that definition. A Bean Scope dictates how Spring manages, shares, and instantiates bean instances across your application. Understanding bean scopes is essential for writing thread-safe, scalable, and memory-efficient enterprise applications.

    1. Core Spring Bean Scopes

    Spring provides two primary core scopes available in any standalone application context:

    • Singleton (Default): Scopes a single bean definition to a single object instance per Spring IoC container. Whenever a bean is requested, Spring returns the exact same shared instance. Best suited for stateless beans like service and DAO components.
    • Prototype: Scopes a single bean definition to create a new object instance every time a request for that bean is made. Ideal for stateful objects where individual callers require isolated instance state.

    2. Web-Aware Spring Bean Scopes

    When running in a web-aware Spring ApplicationContext (such as Spring MVC or Spring Boot web applications), additional scopes become available:

    • Request: Scopes a single bean definition to the lifecycle of a single HTTP request. Each HTTP request receives its own distinct bean instance.
    • Session: Scopes a bean definition to the lifecycle of an HTTP Session. Ideal for user-specific data such as shopping carts or login sessions.
    • Application: Scopes a bean definition to the lifecycle of a ServletContext, shared across all servlets in the web application.
    • Websocket: Scopes a bean definition to the lifecycle of a WebSocket session.

    3. How to Define Bean Scopes

    Spring provides flexible ways to declare the scope of a bean:

    • XML Configuration: Use the scope attribute inside the <bean> tag: <bean id="myBean" class="com.example.MyBean" scope="prototype"/>.
    • Annotation-Based: Annotate your component or @Bean method with @Scope("prototype") or standard constants from ConfigurableBeanFactory / WebApplicationContext.

    4. Best Practices & Considerations

    Keep these key architectural points in mind:

    • Thread Safety: Because singleton beans are shared across threads, ensure their member fields are immutable or stateless.
    • Prototype Destruction: Spring does not manage the complete lifecycle of prototype beans after instantiation; clients are responsible for cleaning up prototype instances and releasing acquired resources.

    📺 Explore More Spring Framework Tutorials

    Continue expanding your Java and Spring knowledge with these related tutorials from our channel:


    Click here to watch on Youtube: 
    https://www.youtube.com/watch?v=dY3ua64_g2Y&list=UUhwKlOVR041tngjerWxVccw

    Click the below Image to Enlarge: 
    What are the different types of spring bean scopes

    See also:

  • All JavaEE Videos Playlist
  • All JavaEE Videos
  • All JAVA EE Links
  • Spring Tutorial
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • Cooking Tutorial
  • Tuesday, 7 July 2015

    Java : Collection Framework : Collections (Singleton)

    🚀 Master the Java Collections Framework!

    Subscribe to Ram N Java for clean Java tutorials, collection framework guides, and clear coding walkthroughs!

    🔔 Subscribe to Ram N Java

    Understanding Singleton Collections in Java

    In standard Java application development, you frequently encounter APIs and business methods that require a collection as an argument, even when you only need to supply a single item. Instantiating a regular ArrayList or HashSet just to hold a single object adds unnecessary memory allocation, boilerplate code, and potential mutability risks. The java.util.Collections utility class addresses this need by providing lightweight, immutable singleton collection factory methods.

    Core Singleton Factory Methods

    The Collections class offers three dedicated static methods to wrap a single element or key-value pair:

    • Collections.singleton(T o): Returns an immutable Set containing only the specified element.
    • Collections.singletonList(T o): Returns an immutable List containing only the specified element.
    • Collections.singletonMap(K key, V value): Returns an immutable Map mapping only the specified key to the specified value.

    Key Characteristics & Behavior

    1. Strict Immutability: All singleton collections returned by these methods are unmodifiable. Attempting to invoke mutator methods (like add(), remove(), or clear()) throws an UnsupportedOperationException.
    2. Minimal Memory Footprint: Unlike dynamic collections that maintain underlying arrays, capacity thresholds, or hash buckets, singleton collections hold only direct references to the specified elements, saving substantial heap memory.
    3. Thread Safety: Because these collections cannot be modified after instantiation, they are inherently thread-safe and safe to share across concurrent routines.
    4. Clean API Interoperability: Easily pass a single item into legacy or third-party methods expecting a collection without unnecessary boilerplate instantiation.

    Why Use Collections.singleton Methods?

    • Cleaner, Readable Code: Expresses your intent clearly in a single, expressive method call.
    • Defensive Programming: Prevents downstream consumers or callers from inadvertently modifying your collection.
    • Optimized Performance: Eliminates array resizing and re-hashing overhead associated with standard mutable collections.

    Recommended Next Videos

    Expand your knowledge of Java collections and immutability with these related tutorials from our channel:

    Tutorials