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

Inversion of Control

Who creates the objects?.

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

In a normal Java program, you create objects yourself, with new. In Spring, it's the other way round. Spring creates the objects, and hands them to you.

  • Normally: you call new
  • In Spring: Spring creates
  • It hands them to you

Who is in control?

Without Spring, your code creates every object, and wires them together by hand. With Spring, you describe the classes, and Spring creates them, wires them, and calls them. Control moves from your code, to the framework. That's why it's called inversion of control.

Without Spring

  • You call newYou wire objectsYou call everything

With Spring

  • Spring calls newSpring wires objectsSpring calls your methods

The container

The place where Spring keeps these objects is called the container. Its Java name is the Application Context. It starts when the app starts. And it creates each controller once, then reuses it for every request.

keyvalue
Containerholds Spring's objects
Java nameApplicationContext
Startswith the app
Controllerscreated once, reused

Created once

We never write new BookController anywhere. The constructor prints a message, when Spring creates the object. And each request prints the object's hash code, a number that identifies it. Run it. The controller was created once, at startup. Both requests used the very same object.

BookController.javajava
@RestController
public class BookController {

    public BookController() {
        System.out.println("Spring created a BookController");
    }

    @GetMapping("/books")
    public String books() {
        System.out.println("Handling a request, on object " + hashCode());
        return "Dune, Circe";
    }
}
Output
$ curl localhost:8080/books
Dune, Circe
$ curl localhost:8080/books
Dune, Circe

── app log ──
Spring created a BookController
Handling a request, on object 1233162869
Handling a request, on object 1233162869
Also uses _curl.sh
curl localhost:8080/books
curl localhost:8080/books

Summary

With inversion of control, Spring creates your objects, and calls your code. The container is the Application Context. Next, beans.

Key takeaways
  • Spring calls new
  • ApplicationContext
  • Created once
Next up: Beans — objects Spring manages