Skip to content

harman-04/spring-bean-scopes

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Spring Bean Scopes Mastery

This project explores how Spring manages the lifecycle and number of instances for beans using the scope attribute.

Singleton vs Prototype

Feature Singleton (Default) Prototype
Instance Count Only one instance per Spring Container. A new instance every time the bean is requested.
Object Reference obj1 == obj2 is True. obj1 == obj2 is False.
Use Case Stateless beans (Services, Daemons). Stateful beans (User sessions, multi-threaded tasks).
Creation Created during container startup (Eager). Created only when requested (Lazy).

Project Structure

  • org.spring.bean.scopes.singleton: Demonstrates shared object state.
  • org.spring.bean.scopes.prototype: Demonstrates independent object states.

Key Experiments

The Address Test

By printing the object address in the Client class, we observe:

  • Singleton: Address of obj1 == Address of obj2
  • Prototype: Address of obj1 != Address of obj2

Modern Annotation Note

While this project uses XML, you can achieve the same result in modern Spring using:

@Component
@Scope("prototype")
public class HelloWorld { ... }

About

Deep-dive into Spring Bean Scopes. Demonstrates the behavioral differences between Singleton (one instance per container) and Prototype (new instance per request) through memory address comparison.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages