Video summary
#6 Dependency Injection using Spring Boot
Main summary
Key takeaways
Main ideas / lessons
-
Dependency Injection (DI) concept: Instead of manually creating dependent objects (e.g., with
new), you let Spring create and manage objects, and then inject the needed dependency into where it’s used. -
Spring Boot and the IOC container:
- When you run a Spring application, Spring creates an IOC (Inversion of Control) container inside the JVM.
- Spring creates objects only for classes you tell it to manage, not for every class in the project.
SpringApplication.run(...)is responsible for creating the application context/container and returns anApplicationContextreference.
-
Why
getBeaninitially failed:- The code attempted to fetch a
Devbean usinggetBean(Dev.class). - Spring threw an error (no qualifying bean) because
Devwas not registered as a managed component yet.
- The code attempted to fetch a
-
How to register a class as a managed bean:
- Add an annotation like
@Componentto the dependency class (e.g.,Dev). - Once annotated, Spring recognizes it as a managed bean and can create it and inject it.
- Add an annotation like
Methodology / steps shown (detailed)
-
Create a new Spring Boot project
- Go to start.spring.io
- Choose:
- Build tool: Maven
- Language: Java
- Spring Boot version: 3.2.5
- Java version: 21
- Packaging: jar
- Do not add “web” dependency to keep it non-web (default Spring Boot setup).
-
Run a basic Spring application
- Use the generated
mainclass withSpringApplication.run(...). - This call:
- Creates the IOC container inside the JVM
- Returns an
ApplicationContextreference
- Use the generated
-
Demonstrate the “manual object creation” approach (without DI)
- Create a class (example:
Dev) with a non-static method (e.g.,build()). - In
main, manually create it:Dev obj = new Dev(); - Call
obj.build(); - Note: this works, but you must manage object lifecycle yourself.
- Create a class (example:
-
Switch to DI using the container
- In
main, avoidnew Dev(). - Obtain the Spring
ApplicationContextfromSpringApplication.run(...). - Fetch the managed dependency via:
context.getBean(Dev.class)
- If
Devis not registered, you get an error: no qualifying bean found.
- In
-
Register the dependency so Spring can create it
- Add
@Componenton the dependency class (Dev). - Re-run the application:
context.getBean(Dev.class)now succeeds- The returned object is managed by Spring
- Effect: Spring injects/provides the dependency to where it’s requested (here, via
getBeaninmain).
- Add
Concepts referenced for the “next layer” idea
- The video sets up a follow-up concept:
- Currently there are two layers:
main -> Dev. - Next, it will consider nested dependencies, e.g.:
Devrequiring aLaptopdependency (Dev->Laptop), and how DI handles that.
- Currently there are two layers:
Speakers / sources featured
- Speaker: The channel host, “D” / “D.ready” (identified in subtitles as: “welcome back aliens my name is D ready”).