π± How Objects (Beans) Are Created in Spring Boot β Explained with Examples
In Spring Boot, objects are managed by the Spring container and are known as beans. Unlike regular Java classes, Spring controls the creation, lifecycle, and scope of these objects.
In this blog, youβll learn:
-
How objects are created in Spring Boot
-
How many instances are created
-
Bean scopes (
singleton
,prototype
, etc.) -
Real code examples
π§ What Is a Spring Bean?
A Spring Bean is simply a Java object that is instantiated, assembled, and managed by Spring's IoC container.
You register a bean by using:
-
@Component
-
@Service
-
@Repository
-
@Controller
-
or manually via
@Bean
in a config class
β Default Object Creation β Singleton Scope
By default, Spring Boot creates only one instance of a bean per container. This is called the singleton scope.
π§ Example:
π‘ Output:
β Only ONE object is created, reused across the app.
π Changing Scope: Prototype (New Object Every Time)
If you want a new object each time, use @Scope("prototype")
.
π§ Example:
π‘ Output:
β
Two objects created, one per request to getBean()
.
π§ͺ Other Bean Scopes
Scope | Description |
---|---|
singleton | (Default) One instance per Spring container |
prototype | New instance every time the bean is requested |
request | One instance per HTTP request (Web apps only) |
session | One per HTTP session |
application | One per ServletContext |
π§ How Are Beans Created Internally?
Internally, Spring Boot uses reflection and dependency injection:
-
Scans for annotated classes using
@ComponentScan
-
Creates bean definitions (
BeanDefinition
) -
Resolves dependencies using constructor injection or field injection
-
Manages lifecycle (
@PostConstruct
,@PreDestroy
, etc.)
π§© Example: Constructor Injection
Spring creates A
first, then passes it to B
automatically.
π¨βπ¬ How to List All Beans Created by Spring Boot?
Add this to main()
:
β You'll see all objects created by Spring, including yours and internal framework beans.
π Singleton vs Prototype β When to Use?
Use Case | Scope to Choose |
---|---|
Shared service (e.g. logging) | singleton |
Non-thread-safe objects | prototype |
Per-user/session customization | request/session |
π Summary
-
Spring Boot uses annotations to create and manage objects (beans)
-
By default, each bean is a singleton
-
You can change the scope with
@Scope("prototype")
and others -
Spring handles injection, lifecycle, and reuse for you
π§ Bonus Tip for Interviews
π£ βIn Spring Boot, object creation is driven by annotations and classpath scanning. Beans are typically singletons, but we can switch to prototype or request scope as needed. Spring uses dependency injection and reflection to wire dependencies automatically.β
Happy Learning :)
No comments:
Post a Comment