AI Hints
Home›Spring Boot Tutorial›Inversion of Control, Beans and Dependency Injection
Spring Boot · Lesson 29 of 120

Beans

Objects Spring manages.

⏱ 2 min read▶ Video at 38:04🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

An object that Spring creates and manages has a special name. It's called a bean.

  • Spring creates it
  • Spring manages it
  • It's a bean

What a bean is

A bean is just a normal Java object, that lives in the container. Spring creates it, and passes it to anyone who needs it. Each bean has a name, usually the class name, starting with a small letter. And by default, there is exactly one of each.

keyvalue
Beanan object in the container
Created bySpring
NamebookController
How manyone, by default

How classes become beans

Spring finds beans in two ways. Classes marked with annotations like at Rest Controller, or at Service, are found by scanning. And methods marked at Bean create beans by hand. We'll see both in this module.

WayExample
Scanning@RestController, @Service, @Component
@Bean methods@Bean Clock clock() { ... }
Spring Boot itselfhundreds of ready-made beans

Looking inside the container

Here, our controller asks for the Application Context itself. Get bean definition count, counts all the beans. Contains bean checks for a bean, by name. Run it. There are hundreds of beans, mostly made by Spring Boot. Our controller is one of them, named bean controller. And there's no book service, because we haven't written one yet.

BeanController.javajava
@RestController
public class BeanController {

    private final ApplicationContext context;

    public BeanController(ApplicationContext context) {
        this.context = context;
    }

    @GetMapping("/beans")
    public String beans() {
        return "Beans in the container: " + context.getBeanDefinitionCount()
            + "\nbeanController? " + context.containsBean("beanController")
            + "\nbookService? " + context.containsBean("bookService");
    }
}
Output
Beans in the container: 353
beanController? true
bookService? false
Also uses _curl.sh
curl localhost:8080/beans

Summary

A bean is an object that lives in Spring's container. Spring finds them by scanning, or from at Bean methods. Next, dependency injection.

Key takeaways
  • Bean = managed object
  • Found by scanning
  • One of each
Next up: Dependency Injection — Spring passes what you need