Saturday, 5 April 2025

 

🌱 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:


@Component public class MyService { public MyService() { System.out.println("MyService bean created!"); } }

@RestController public class MyController { @Autowired private MyService service1; @Autowired private MyService service2; @GetMapping("/test") public String test() { return "Are both services same? " + (service1 == service2); } }

πŸ’‘ Output:

MyService bean created! Are both services same? true

βœ… 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:


@Component @Scope("prototype") public class MyPrototypeService { public MyPrototypeService() { System.out.println("PrototypeService instance created!"); } }


@RestController public class TestController { @Autowired private ApplicationContext context; @GetMapping("/proto") public String test() { MyPrototypeService s1 = context.getBean(MyPrototypeService.class); MyPrototypeService s2 = context.getBean(MyPrototypeService.class); return "Are both prototype beans same? " + (s1 == s2); } }

πŸ’‘ Output:


PrototypeService instance created! PrototypeService instance created! Are both prototype beans same? false

βœ… Two objects created, one per request to getBean().


πŸ§ͺ Other Bean Scopes

ScopeDescription
singleton(Default) One instance per Spring container
prototypeNew instance every time the bean is requested
requestOne instance per HTTP request (Web apps only)
sessionOne per HTTP session
applicationOne per ServletContext

🧠 How Are Beans Created Internally?

Internally, Spring Boot uses reflection and dependency injection:

  1. Scans for annotated classes using @ComponentScan

  2. Creates bean definitions (BeanDefinition)

  3. Resolves dependencies using constructor injection or field injection

  4. Manages lifecycle (@PostConstruct, @PreDestroy, etc.)


🧩 Example: Constructor Injection


@Component public class A { public A() { System.out.println("A created"); } } @Component public class B { private final A a; @Autowired public B(A a) { this.a = a; System.out.println("B created with A"); } }

Spring creates A first, then passes it to B automatically.


πŸ‘¨β€πŸ”¬ How to List All Beans Created by Spring Boot?

Add this to main():


public static void main(String[] args) { ConfigurableApplicationContext ctx = SpringApplication.run(MyApp.class, args); String[] beans = ctx.getBeanDefinitionNames(); Arrays.sort(beans); for (String name : beans) { System.out.println(name); } }

βœ… You'll see all objects created by Spring, including yours and internal framework beans.


πŸ” Singleton vs Prototype – When to Use?

Use CaseScope to Choose
Shared service (e.g. logging)singleton
Non-thread-safe objectsprototype
Per-user/session customizationrequest/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