Cheatsheet

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).

Diagram (UML)

ApplicationContextAthleteBookingController30BookingServiceBoxConfig«i»SpotRepository«i»NotifierInMemorySpotRepositoryEmailNotifier

Key pieces

  • ApplicationContext: the container; extends BeanFactory and adds events, i18n, resources and eager singleton creation
  • AnnotationConfigApplicationContext: the implementation that starts from @Configuration classes
  • @Configuration + @Bean: one recipe per bean; the bean name is the method name
  • getBean(Class), getBean(String), getBean(String, Class): looking beans up by hand (almost never in your own code)
  • Bean: any object whose lifecycle the container manages

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);
    }
}

Remember for the exam

  • IoC is the principle (someone else controls creation); DI is the technique (dependencies come in through constructor, setter or field)
  • The default scope is singleton, one instance per container, created at startup
  • Constructor injection is the recommended one; it allows final fields and tests without Spring
  • If a class has a single constructor, Spring uses it without @Autowired
  • The container is shut down with close() (or try-with-resources), which calls the destroy callbacks
  • In Spring Boot you don't create the context, SpringApplication.run() does

Exam traps

  • getBean(Notifier.class) with two beans of that type throws NoUniqueBeanDefinitionException; it does not return the first one
  • A name that doesn't exist throws NoSuchBeanDefinitionException; it never returns null
  • A cycle between constructors (A needs B and B needs A) fails at startup with BeanCurrentlyInCreationException
  • BeanFactory creates singletons lazily; ApplicationContext, at startup

← The IoC container · Run it