Lesson 4 / 25

Beans and the Application Context

Inversion of control.

The container builds the object graph

In Spring, the application context creates objects called beans, injects their dependencies and manages their lifecycle. Classes become beans through stereotype annotations found by component scanning (@Component, @Service, @Repository, @RestController) or through @Bean methods in @Configuration classes. This inversion of control keeps classes focused on their job and makes them easy to test, because dependencies can be replaced with test doubles.

Wire objects, externalise settings

The Spring container creates and connects your objects and binds configuration into typed classes.

Three ideas: beans and the container, constructor injection, typed properties.
Figure 2.1 — Beans, injection and properties.

A stage manager

Actors (beans) do not hire their own crew; the stage manager (the container) assigns everyone their partners before the show starts.

Use stereotypes for intent

@Service, @Repository and @RestController all create beans but also document each class's role, and @Repository adds exception translation.

Quick check: What is a Spring bean?

  • A Java coffee class
  • An object created and managed by the Spring container
  • A database table
  • A configuration file
Answer

An object created and managed by the Spring container — The container owns bean lifecycles.