0
0
SpringbootConceptBeginner · 3 min read

What is Bean in Spring Boot: Simple Explanation and Example

In Spring Boot, a bean is an object that is managed by the Spring framework's container. Beans are created, configured, and connected automatically by Spring to help build applications with reusable components.
⚙️

How It Works

Think of a bean in Spring Boot like a tool in a toolbox that Spring keeps track of for you. Instead of you creating and managing these tools manually, Spring automatically creates these objects and manages their life cycle. This means Spring knows when to create them, how to connect them with other tools, and when to clean them up.

This automatic management is done by the Spring container, which reads your code or configuration to find out which objects should be beans. When your application runs, Spring creates these beans and injects them where needed, so your code can focus on what it needs to do without worrying about object creation.

💻

Example

This example shows a simple Spring Boot bean defined with @Component and used in another class with @Autowired.

java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;

@SpringBootApplication
public class BeanExampleApplication {
    public static void main(String[] args) {
        var context = SpringApplication.run(BeanExampleApplication.class, args);
        MyService service = context.getBean(MyService.class);
        service.showMessage();
    }
}

@Component
class MyService {
    public void showMessage() {
        System.out.println("Hello from the Spring Bean!");
    }
}
Output
Hello from the Spring Bean!
🎯

When to Use

Use beans whenever you want Spring Boot to manage your objects automatically. This is especially helpful for services, repositories, or components that your application needs to reuse or share. Beans make your code cleaner and easier to test because Spring handles the creation and connection of these objects.

For example, when building a web app, you create beans for database access, business logic, or external API calls. Spring then injects these beans where needed, so you don't have to manually create or pass objects around.

Key Points

  • A bean is an object managed by the Spring container.
  • Spring creates, configures, and injects beans automatically.
  • Beans help organize code into reusable and testable parts.
  • Use annotations like @Component or @Service to define beans.

Key Takeaways

A bean is a Spring-managed object created and injected automatically.
Beans simplify your code by handling object creation and dependencies.
Use beans for services, repositories, and components in your app.
Annotations like @Component mark classes as beans for Spring to manage.