DEV Community

Phoenix
Phoenix

Posted on

Spring Beans, Context, Spring IoC container

Spring Beans
we hear a lot about beans when we are working with spring

A Spring Bean is any Java object that is instantiated, configured, and managed by the Spring IoC container.

a Bean is a POJO(Plain Old Java Object)
But not every POJO is a Bean.

A Bean = POJO + managed by Spring

What does “managed by Spring” mean?
Spring:

  • Creates the object
  • Stores it in the container
  • Injects its dependencies
  • Controls its lifecycle
  • Destroys it when the app shuts down
  • Only such objects are called Beans.

It is not mandatory that every class inside your application should be beans, like (utilities classes)

How spring knows which needs to be maintained?

  • with the help of configurations that we supply either through XML files or Annotations

Context
context is like a memory location where we add all the object instances that we want the framework to manage. by default spring doesn't know any of the objects that we define in the application. to enable spring to see your object you need to add them to the context.

We add classes to the Spring context by annotating them so that Spring can create and manage their objects as beans.

*Spring IoC container *
The Spring IoC Container is the core part of Spring that creates, manages, and injects application objects (beans) and controls their lifecycle.

Here’s the big picture

When a Spring (or Spring Boot) application starts, the first thing it creates is something called the ApplicationContext.
This ApplicationContext is the Spring IoC container.

You can think of it as Spring’s brain and memory.

What does this IoC container do?

It looks at your project and searches for classes marked with things like:

  • @Component
  • @Service
  • @Repository
  • @Controller

These annotations tell Spring:

“You are allowed to manage this class.”

Spring then creates objects of those classes and stores them inside the ApplicationContext.

These objects are called Spring Beans.

Bean→ the object Spring creates from that class

Context → where Spring stores and manages those objects

In simple words:
Spring creates a context (IoC container), puts your beans inside it, and then runs your application using those beans.

Top comments (0)