Ad Code

Ad code

Understanding Bean Scopes in Spring Framework

In the Spring Framework, beans are the heart of the application. But how they behave and how long they live depends on something known as Bean Scopes. Understanding bean scopes is crucial when developing scalable, testable, and efficient applications.

What is a Bean Scope?

A bean scope defines the lifecycle and visibility of a bean within the Spring context. In simple words, it answers: How many instances of this bean should Spring create? and Who can access it?

Available Bean Scopes

Spring provides several scopes, but the most commonly used are:

  • Singleton (default)
  • Prototype
  • Request (Web only)
  • Session (Web only)
  • Application (Web only)

Visual Overview

Here's a diagram to help you visualize the bean scopes:

Bean Scope Diagram

1. Singleton Scope

Definition: Only one instance of the bean is created for the entire Spring container.

Use Case: Configuration classes, service layers.

Example:

@Component
@Scope("singleton") // optional, as it's the default
public class MySingletonBean {
    public MySingletonBean() {
        System.out.println("Singleton Bean Created");
    }
}

Test Scenario:

@SpringBootTest
public class BeanScopeTest {

    @Autowired
    private MySingletonBean bean1;

    @Autowired
    private MySingletonBean bean2;

    @Test
    void testSingleton() {
        assertSame(bean1, bean2); // They point to the same instance
    }
}

2. Prototype Scope

Definition: A new instance is created every time the bean is requested.

Use Case: Stateful objects like tools, commands, or form data beans.

Example:

@Component
@Scope("prototype")
public class MyPrototypeBean {
    public MyPrototypeBean() {
        System.out.println("Prototype Bean Created");
    }
}

Test Scenario:

@SpringBootTest
public class PrototypeTest {

    @Autowired
    private ApplicationContext context;

    @Test
    void testPrototype() {
        MyPrototypeBean bean1 = context.getBean(MyPrototypeBean.class);
        MyPrototypeBean bean2 = context.getBean(MyPrototypeBean.class);

        assertNotSame(bean1, bean2); // Each call creates a new instance
    }
}

3. Request Scope (Web Only)

Definition: A new bean is created for every HTTP request.

Use Case: Web controllers handling request-specific data.

Example:

@Component
@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class RequestBean {
    // Data specific to one HTTP request
}

Why proxy mode? Because request-scoped beans are created per request, and we need to safely inject them into singleton beans like controllers.

4. Session Scope (Web Only)

Definition: A bean lives throughout the lifespan of a user session.

Use Case: Shopping cart, session preferences.

Example:

@Component
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class SessionBean {
    private List<String> cartItems = new ArrayList<>();
}

5. Application Scope (Web Only)

Definition: A single bean shared across all sessions and requests in a web application.

Use Case: Caching, static metadata.

Example:

@Component
@Scope(value = WebApplicationContext.SCOPE_APPLICATION)
public class ApplicationBean {
    // Shared configuration or metadata
}

Choosing the Right Scope

Here’s a quick comparison to help you decide:

Scope Instances Best For
Singleton One per container Stateless Services
Prototype One per injection Stateful/Temporary Beans
Request One per HTTP request Request-level Data
Session One per user session Shopping carts, preferences
Application One per web app Shared Metadata

Conclusion

Understanding bean scopes helps you control how Spring manages the lifecycle of your components. Singleton is the most common and efficient, but use Prototype or web scopes when your application's behavior requires it. Choosing the right scope means more predictable performance and fewer bugs.


Post a Comment

0 Comments

Ad code

Ad Code