DEV Community

Cover image for What is a Bean in Spring Boot?
Varun Patil
Varun Patil

Posted on

What is a Bean in Spring Boot?

If you are learning Spring Boot, one term you’ll hear again and again is “Bean”. But what exactly is a Bean, and why is it so important? Let’s break it down in simple terms for developers.

1. What is a Bean?
In Spring, a Bean is simply an object managed by the Spring IoC (Inversion of Control) container.

Instead of manually creating objects using new in your code, Spring creates and manages the objects for you. This allows Spring to:

  1. Automatically inject dependencies into classes.
  2. Manage the lifecycle of objects (initialization and destruction).
  3. Promote loose coupling and reusability.

In short, a bean is just a Spring-managed object.

2. Beans Are Not Just Models
Many developers assume beans are only for model classes (like Car, User, etc.), but that’s not true. Beans can be:

  • Models / Entities
  • Services
  • Repositories / DAOs
  • Controllers
  • Configuration classes

Basically, any class you want Spring to manage can be a bean.

3. How to Create Beans in Spring Boot
a) Using Annotations (Recommended in Spring Boot)
Spring Boot automatically scans your packages for components and creates beans for you.

@Component
public class Car {
    public void drive() {
        System.out.println("Driving a Mercedes");
    }
}

@Service
public class CarService {
    private final Car car;

    @Autowired
    public CarService(Car car) {
        this.car = car;
    }

    public void startJourney() {
        car.drive();
    }
}

Enter fullscreen mode Exit fullscreen mode

b) Using Configuration Class with @bean
You can also define beans in a central configuration class:

@Configuration
public class AppConfig {

    @Bean
    public Car car() {
        return new Car();
    }

    @Bean
    public CarService carService() {
        return new CarService(car());
    }
}

Enter fullscreen mode Exit fullscreen mode

4. Why Beans Matter

  • Inversion of Control (IoC): Spring creates objects and injects dependencies, not your code.
  • Dependency Injection (DI): Makes your code loosely coupled, reusable, and testable.
  • Lifecycle Management: Spring can manage bean lifecycle (@PostConstruct, @PreDestroy, or init-method / destroy-method).
  • Reusability:A single bean can be used across multiple services, controllers, and other beans. **
  • Bean Lifecycle (Brief Overview)**

  • Spring instantiates the bean

  • Injects dependencies

  • Calls initialization methods

  • Bean is ready to use

  • On shutdown, calls destroy methods

6. Conclusion

  • A bean is simply a Spring-managed object.
  • Beans allow Spring to handle object creation, wiring, and lifecycle, letting you focus on building business logic.
  • Modern Spring Boot uses annotations + component scanning, so you rarely need XML anymore.

Top comments (0)