The IoC container
- Key idea
- Your classes don't create their dependencies, they receive them. The Spring container (the ApplicationContext) reads the configuration, creates the beans and injects them into each other. That is inversion of control (IoC), and its concrete form, dependency injection (DI).
- In the box
- The box's booking service built its own parts with new. Hand it its dependencies through the constructor, let the ApplicationContext create and wire them, and learn what the exam asks about all of it.
The athlete sends POST booking to BookingController, which calls book() on NewingBookingService, highlighted in red. The service is wired straight to InMemorySpotRepository and EmailNotifier.
The diagram is unchanged. InMemorySpotRepository and EmailNotifier are highlighted: the service creates them with new and they can't be replaced.
BookingService appears, highlighted with the SpotRepository and Notifier interfaces that are injected into it. InMemorySpotRepository implements SpotRepository and EmailNotifier implements Notifier.
The ApplicationContext platform appears with BoxConfig, both highlighted. A @Bean packet travels from BoxConfig to BookingService: the configuration tells the container how to create it.
Packets travel along the chain: POST booking from the athlete to the controller, book() to the highlighted service, and from the service takeSpot() towards SpotRepository and send() towards Notifier.
Without the Spring context: BookingService with its two interfaces and, in place of the real implementations, two highlighted test doubles, wod -> 0 and recorder.
The context shows a third block, smsNotifier, which also implements Notifier. Notifier, EmailNotifier and smsNotifier are highlighted: two candidates for the same type.
Only Coach and Schedule are left in the context, both in red, with arrows going from one to the other in both directions: a cycle that prevents creating either of them.
Final view: the athlete, the controller and BookingService inside the ApplicationContext, with BoxConfig, the SpotRepository and Notifier interfaces and their implementations.
Step 1 of 9
A service that does it all itself
In the box, BookingController takes an athlete's booking and calls NewingBookingService. To do its job the service needs two collaborators: a repository that keeps track of the spots and a notifier that sends the confirmation e-mail.
The service creates them itself, with new, in its own fields.
Step 2 of 9
Tied to its parts
That new has consequences:
- You can't test it without a real database (or whatever is behind the repository). There is no way to slip in a test double.
- You can't switch the notifier to SMS without editing and recompiling the service.
- Every service that needs a repository creates its own, so there are several copies with different state.
Step 3 of 9
Be handed your parts: dependency injection
Turn it around. BookingService declares what it needs in its constructor, and it declares it with interfaces: SpotRepository and Notifier. It no longer knows which implementation it gets, nor does it care.
This is dependency injection (DI): dependencies come in from outside. It comes in three flavours:
- Constructor (the recommended one): mandatory dependencies,
finalfields, a complete object from the first moment. - Setter: for optional or changing dependencies.
- Field (
@Autowiredon the attribute): convenient, but it hides the dependencies and makes tests harder.
Step 4 of 9
Someone has to call new: the ApplicationContext
If the service no longer calls new, somebody has to. That somebody is the Spring IoC container, the ApplicationContext.
You give it a configuration (here, the BoxConfig class with one @Bean method per object) and it:
- Reads the bean definitions.
- Creates each bean in the order its dependencies require.
- Injects them into each other: it sees that
bookingService(...)asks for aSpotRepositoryand aNotifierand passes in the two beans it already has.
A bean is just that: an object whose lifecycle the container manages.
Step 5 of 9
A booking, with everything wired
Now follow the request. The athlete sends POST /api/bookings?athlete=Ana&wod=Fran, the controller calls book() and the service uses its two injected dependencies: takeSpot() on the repository and send() on the notifier.
The test asks the context for beans in two ways:
- By type:
getBean(BookingService.class). - By name and type:
getBean("notifier", Notifier.class). The name of a@Beanbean is its method name.
And it checks something important: asking for the bean twice returns the same instance. The default scope is singleton: one object per container, created at startup.
Step 6 of 9
The reward: tests without Spring
Because BookingService receives its dependencies, a unit test needs no container. You pass two doubles written as lambdas (both interfaces have a single method):
- a fake repository that says 0 spots are left;
- a notifier that records whom it told.
The test is plain Java: new BookingService(fake, recorder), and it runs in milliseconds.
Step 7 of 9
When the lookup fails
Back to the container. If you add a second notifier, smsNotifier, there are now two beans of type Notifier. What does getBean(Notifier.class) return?
Nothing: it throws NoUniqueBeanDefinitionException. Spring doesn't choose for you. And if you ask for a name that doesn't exist, getBean("coach"), it throws NoSuchBeanDefinitionException. It never returns null.
On the difference between the two container interfaces:
BeanFactoryis the core: it creates beans when asked (lazily).ApplicationContextextends it and creates singletons at startup (so errors surface early), publishes events, resolves i18n messages and loads resources.
Step 8 of 9
Trap: circular dependencies
Coach needs a Schedule in its constructor and Schedule needs a Coach in its own. To create the first you need the second, and for the second, the first.
Spring detects it at startup and the context never comes up: the root cause is BeanCurrentlyInCreationException.
Step 9 of 9
Recap
You started with a service that called new on everything and ended with a container that assembles it:
- IoC: the container controls creation; DI: dependencies come in through the constructor (best), a setter or a field.
- ApplicationContext reads the configuration, creates the beans at startup and wires them.
- Singleton by default: one instance per container.
- Lookup by type needs a unique candidate; looking up something that doesn't exist throws, never returns
null. - Cycles between constructors break startup.
Code
NewingBookingService.java
/** Before: the service builds its own collaborators, so nobody can swap them. */
public class NewingBookingService {
private final InMemorySpotRepository spots = new InMemorySpotRepository(12);
private final EmailNotifier notifier = new EmailNotifier();
public Booking book(String athlete, String wod) {
int left = spots.takeSpot(wod);
if (left < 0) {
throw new ClassFullException(wod);
}
notifier.send(athlete, "See you at " + wod);
return new Booking(athlete, wod, left);
}
}NewingBookingService.java
/** Before: the service builds its own collaborators, so nobody can swap them. */
public class NewingBookingService {
private final InMemorySpotRepository spots = new InMemorySpotRepository(12);
private final EmailNotifier notifier = new EmailNotifier();
public Booking book(String athlete, String wod) {
int left = spots.takeSpot(wod);
if (left < 0) {
throw new ClassFullException(wod);
}
notifier.send(athlete, "See you at " + wod);
return new Booking(athlete, wod, left);
}
}BookingService.java
public class BookingService {
private final SpotRepository spots;
private final Notifier notifier;
// The dependencies come in from outside: the class no longer chooses them.
public BookingService(SpotRepository spots, Notifier notifier) {
this.spots = spots;
this.notifier = notifier;
}
public Booking book(String athlete, String wod) {
int left = spots.takeSpot(wod);
if (left < 0) {
throw new ClassFullException(wod);
}
notifier.send(athlete, "See you at " + wod);
return new Booking(athlete, wod, left);
}
}BoxConfig.java
@Configuration
public class BoxConfig {
@Bean
public SpotRepository spotRepository() {
return new InMemorySpotRepository(12);
}
@Bean
public Notifier notifier() {
return new EmailNotifier();
}
@Bean // Spring passes in the two beans above: that is dependency injection
public BookingService bookingService(SpotRepository spots, Notifier notifier) {
return new BookingService(spots, notifier);
}
}ContainerTest.java
@Test
void theContainerBuildsAndWiresTheBeans() {
try (var context = new AnnotationConfigApplicationContext(BoxConfig.class)) {
BookingService service = context.getBean(BookingService.class); // by type
Notifier notifier = context.getBean("notifier", Notifier.class); // by name + type
service.book("Ana", "Fran");
assertThat(((EmailNotifier) notifier).outbox()).containsExactly("Ana: See you at Fran");
assertThat(context.getBean(BookingService.class)).isSameAs(service); // singleton by default
}
}BookingServiceTest.java
@Test
void booksWithFakesAndNoSpringAtAll() {
List<String> sent = new ArrayList<>();
SpotRepository oneSpotLeft = wod -> 0; // a fake: the last spot
Notifier recorder = (athlete, msg) -> sent.add(athlete);
BookingService service = new BookingService(oneSpotLeft, recorder);
assertThat(service.book("Ana", "Fran").spotsLeft()).isZero();
assertThat(sent).containsExactly("Ana");
}ContainerTest.java
@Test
void lookupsFailLoudly() {
try (var context = new AnnotationConfigApplicationContext(BoxConfig.class, ExtraNotifier.class)) {
assertThatThrownBy(() -> context.getBean(Notifier.class))
.isInstanceOf(NoUniqueBeanDefinitionException.class); // two Notifier beans
assertThatThrownBy(() -> context.getBean("coach"))
.isInstanceOf(NoSuchBeanDefinitionException.class); // no bean with that name
}
}CircularDependencyTest.java
@Component
static class Coach {
Coach(Schedule schedule) { }
}
@Component
static class Schedule {
Schedule(Coach coach) { } // Coach needs Schedule, Schedule needs Coach
}
@Test
void constructorCyclesCannotBeResolved() {
assertThatThrownBy(() -> new AnnotationConfigApplicationContext(Coach.class, Schedule.class))
.hasRootCauseInstanceOf(BeanCurrentlyInCreationException.class);
}BoxConfig.java
@Configuration
public class BoxConfig {
@Bean
public SpotRepository spotRepository() {
return new InMemorySpotRepository(12);
}
@Bean
public Notifier notifier() {
return new EmailNotifier();
}
@Bean // Spring passes in the two beans above: that is dependency injection
public BookingService bookingService(SpotRepository spots, Notifier notifier) {
return new BookingService(spots, notifier);
}
}