DEV Community

Cover image for what is the Difference Between Singleton and Prototype Scope in Spring?
realNameHidden
realNameHidden

Posted on

what is the Difference Between Singleton and Prototype Scope in Spring?

Learn the difference between singleton and prototype scope in Spring with simple explanations, real Java examples, and best practices for beginners learning dependency injection.


What Is the Difference Between Singleton and Prototype Scope in Spring?

Introduction

Imagine you run a café. Some customers want to reuse the same coffee cup for multiple refills, while others prefer a fresh cup every single time. In the world of Java programming, Spring manages its objects (beans) in a very similar way. Some objects should be created only once and reused, while others should be created every time they’re requested.

This is where understanding singleton and prototype scope in Spring becomes essential. Bean scope determines how many instances of a bean Spring creates and how long those instances live. Choosing the right scope can significantly improve your application’s performance, stability, and readability. In this blog, we’ll break down these two scopes, explain how they differ, show when to use each, and walk through practical Java examples to make everything crystal clear.


Core Concepts

Spring Beans are objects managed by the Spring IoC container. Bean scope controls the lifecycle and instance creation of these beans. The two most widely used scopes in everyday Spring Boot development are:


1. Singleton Scope (Default Scope)

Definition:
Spring creates only one instance of the bean for the entire application context. Every injection point receives the same object.

Analogy:
Like a single coffee machine shared by all employees in an office.

Use Cases:

  • Stateless service classes
  • Business logic handlers
  • Utility components
  • Configuration objects

Benefits:

  • Memory efficient
  • Better performance due to reusability
  • Consistent behavior across application

Risks:

  • Cannot store request-specific or user-specific data
  • Becomes unsafe if used to store mutable shared state

2. Prototype Scope

Definition:
Spring creates a new bean instance every time it is requested from the container.

Analogy:
A fresh coffee cup given to every customer.

Use Cases:

  • Request-level or temporary objects
  • Stateful beans
  • Components with mutable internal state
  • Batch processing units

Benefits:

  • Fresh instance for every request
  • Ideal for stateful operations
  • Avoids concurrency issues

Risks:

  • Higher memory consumption
  • Difficult to track lifecycle
  • Becomes dangerous when injected into singletons

Key Difference (Quick Summary)

Feature Singleton Scope Prototype Scope
Instances One instance reused New instance every request
Memory Usage Low Higher
Best For Services, utilities Stateful, temporary tasks
Lifecycle Managed By Spring (fully) Only at creation time
Thread Safety Risky if mutable Safe for stateful logic

Understanding this difference is critical when you learn Java and build scalable systems using Spring.


Code Examples


Example 1 — Singleton Bean (default)

package com.example.scope;

import org.springframework.stereotype.Service;

@Service // Default scope: singleton
public class GreetingService {

    public String message() {
        return "Hello from Singleton Bean";
    }
}
Enter fullscreen mode Exit fullscreen mode

Testing Singleton Behavior

@Autowired
GreetingService s1;

@Autowired
GreetingService s2;

System.out.println(s1 == s2); // true — same instance
Enter fullscreen mode Exit fullscreen mode

✔ Only one instance is created.


Example 2 — Prototype Bean

package com.example.scope;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("prototype") // New instance for every request
public class TaskProcessor {

    public String process() {
        return "Processed at " + System.nanoTime();
    }
}
Enter fullscreen mode Exit fullscreen mode

Testing Prototype Behavior

@Autowired
TaskProcessor p1;

@Autowired
TaskProcessor p2;

System.out.println(p1 == p2); // false — different instances
Enter fullscreen mode Exit fullscreen mode

✔ Each request creates a separate object instance.


Best Practices

⭐ Use Singleton for Stateless Beans

Service classes should always be stateless and singleton.


⭐ Use Prototype Only When Needed

Prototype beans are useful but can create memory overhead when overused.


⭐ Never inject Prototype into Singleton directly

It breaks expected behavior since prototype will be created only once.

Instead use:

  • ObjectFactory<>
  • Provider<>
  • Lookup methods

⭐ Avoid Storing Global State in Singletons

It leads to concurrency issues and unpredictable behavior.


⭐ Log bean instantiation during debugging

Helps visualize how many objects are created.


Conclusion

Understanding the difference between singleton and prototype scope in Spring is crucial for designing efficient, predictable, and scalable Spring Boot applications. Singleton beans give you performance and consistency, while prototype beans offer flexibility and state isolation. Knowing when to use each scope helps you avoid concurrency risks, memory problems, and unexpected behavior in your applications.

Whether you're building a small REST API or a large enterprise solution, mastering bean scopes will make you a stronger Spring developer. Try implementing both scopes in a simple demo project—you’ll immediately notice the difference in instance creation and lifecycle.


Top comments (0)