This document discusses improving testability and maintainability of applications through dependency injection with Spring. It begins by showing how plain Java code without separation of concerns is difficult to test. It then introduces the service locator pattern, which improves testability but has downsides like being a single point of failure. Finally, it explains how Spring implements inversion of control through its core functionality, allowing for dependency injection that is more extensible and testable than the service locator pattern alone. Key Spring annotations and configurations are also outlined.
3. Plain Java
No separation of
concerns (SoC), not
testable
01
Service Locator
Pattern
A common pattern for
improving testability
02
Conclusions
What now?
04
IoC & Spring
How do Spring and
Spring Boot make life
easier?
03
8. Testing this Code
prepare(...) {
}
MacronutrientsProvider mp =
new MacronutrientsProvider(...)
//..
mp.fetch() fetch(...)
{
}
new(...) {
}
HTTP call
WaffleCreator MacronutrientsProvider
We have no
control over the
HTTP call
22. WaffleCreator
prepare(...) {
}
MacronutrientsProvider mp =
ServiceLocator.get(MacronutrientsProvider.class,“nosugar);
mp.fetch();
Config
init(...) {
}
ServiceLocator.put(“nosugar”,
new MacronutrientsProvider(...),
MacronutrientsProvider.class));
Using the Generic Service Locator
23. WaffleCreator
prepare(...) {
}
MacronutrientsProvider mp =
ServiceLocator.get(MacronutrientsProvider.class,“nosugar);
mp.fetch();
Config
init(...) {
}
ServiceLocator.put(“nosugar”,
new MacronutrientsProvider(...),
MacronutrientsProvider.class));
Using the Generic Service Locator
24. But now too much boilerplate code!
ServiceLocator.get(HttpClient.class, "with timeouts");
ServiceLocator.get(MacronutrientsProvider.class, "high sugar");
ServiceLocator.get(WaffleDatabase.class, "mysql");
33. Key Annotations
@Bean
added when using
java config
@Configuration
added for classes
containing @Bean
declarations
@Component
added when using
component scan
@Repository
component that is a
repository
@Service
component that is a
business service
@Qualifier
mocks/stubs bean
@MockBean
specifies name of the
injected bean
@SpringBootTest
automatically bootstraps
IoC
34. Java Config
Beans are not polluted
with annotations
Component Scan
No need to add additional
configuration classes
XML
Not used much nowadays
Bean Registration
There are three different ways that
Spring can register dependencies.
36. CREDITS: This presentation
template was created by Slidesgo,
including icons by Flaticon, and
infographics & images by Freepik
Thanks!
Repo: github.com:pilloPl/waffles.git
Slides: https://bit.ly/spring-di
@LaylaCodesIt
@JakubPilimon