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)
classDiagram
direction LR
class ApplicationContext {
<<interface>>
+getBean(Class) T
+getBean(String, Class) T
+close()
}
class BeanFactory {
<<interface>>
}
class BoxConfig {
<<@Configuration>>
+spotRepository() SpotRepository
+notifier() Notifier
+bookingService(SpotRepository, Notifier) BookingService
}
class BookingService {
<<bean>>
-spots: SpotRepository
-notifier: Notifier
+book(athlete, wod) Booking
}
class SpotRepository {
<<interface>>
}
class Notifier {
<<interface>>
}
BeanFactory <|-- ApplicationContext
ApplicationContext ..> BoxConfig : reads
ApplicationContext ..> BookingService : creates and injects
BookingService --> SpotRepository
BookingService --> Notifier
SpotRepository <|.. InMemorySpotRepository
Notifier <|.. EmailNotifierKey pieces
ApplicationContext: the container; extendsBeanFactoryand adds events, i18n, resources and eager singleton creationAnnotationConfigApplicationContext: the implementation that starts from@Configurationclasses@Configuration+@Bean: one recipe per bean; the bean name is the method namegetBean(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
finalfields 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 throwsNoUniqueBeanDefinitionException; it does not return the first one- A name that doesn't exist throws
NoSuchBeanDefinitionException; it never returnsnull - A cycle between constructors (A needs B and B needs A) fails at startup with
BeanCurrentlyInCreationException BeanFactorycreates singletons lazily;ApplicationContext, at startup