Loading
Autowiring-tutorial
The Spring Framework is built on top of the powerful idea that the framework not you should manage the objects in your application.
These managed objects are known as Spring Beans, and understanding how they are created, configured, and destroyed is essential for mastering Spring development.


What is a Spring Bean?

A Spring Bean is any Java object that the Spring IoC Container creates and manages.

Spring is responsible for:

  • Creating the object
  • Injecting its dependencies
  • Managing its lifecycle
  • Destroying it when the application ends

Declaring a Spring Bean (Most Common Way)

@Component
public class MyService {
}

Classes marked with:

  • @Component
  • @Service
  • @Repository
  • @Controller
are automatically detected and created as beans.


How Spring Creates Beans

Spring uses component scanning to locate classes and create beans.


Example configuration:

@Configuration
@ComponentScan("com.example")
public class AppConfig {
}

When your application starts:

  1. Spring scans the package
  2. Finds component classes
  3. Creates bean instances
  4. Injects dependencies
  5. Stores the beans inside the IoC container
This automation makes Spring applications clean and scalable.


Bean Scopes — How Many Instances Does Spring Create?

A Bean’s scope defines how often a new instance is created.

1. Singleton (Default)

One instance for the entire application.

@Scope("singleton")
public class MyBean {}


2. Prototype

Creates a new instance every time it is requested.

@Scope("prototype")
public class MyBean {}


3. Request

One instance per HTTP request (Web apps).

@Scope("request")


4. Session

One instance per user session.

@Scope("session")


5. Application

One instance per servlet context.


Understanding the Spring Bean Lifecycle

Spring manages a bean from the moment it is created until the moment it is destroyed.
Here’s the entire process step-by-step:


1. Bean Instantiation

Spring first creates an instance of your class (calls the constructor).