Enrol to start learning
Reading is open to everyone. Enrolling is free, and it is what unlocks the audio lessons, practice tests and progress tracking.
30.5.2. Dependency Injection (DI)
This section
Practice test
11 questions on this section. Wrong answers show you what to read again.
Sign up to take itWhole chapter
Revision test
Mixed questions from across the chapter. Your answers get marked.
Sign up to take itQuick
Flashcard drill
4 cards from this lesson. Good the night before a test.
Try these first
- 1.
What does Dependency Injection do?
Hint
Think about how it contrasts with a class creating its own dependencies.
- 2.
Which annotation is typically used in Field Injection?
Hint
This annotation helps the framework know which dependencies to inject.
- 3.
What is the main advantage of Dependency Injection?
- A. Increased coupling
- B. Improved modularity
- C. Reduced testability
Hint
Think of how you might change a part of the code without affecting others.
- 4.
True or False: Field Injection requires explicit constructors.
- True
- False
Hint
Consider whether constructors are needed when dependencies are injected directly.
- 5.
Create a simple class structure using Dependency Injection. Define a class Car that has a dependency on Engine. Illustrate with both Constructor and Setter Injection, and explain when each approach is preferable.
Hint
Use a constructor for things that must exist and setters for those that can wait.
- 6.
Discuss how Dependency Injection can lead to better unit testing practices. Provide an example scenario where DI improves the testability of a class.
Hint
Think about how you would isolate a class from its dependencies while testing.
Exercises
Total Questions
2
Estimated Time
4 min
Passing Score
70%
Instructions
- Read each question carefully
- You can use hints if you need help
- Complete all questions before submitting
4 more questions available
Enrol freeQuiz
Total Questions
2
Estimated Time
4 min
Passing Score
70%
Instructions
- Read each question carefully
- You can use hints if you need help
- Complete all questions before submitting
1 more question available
Enrol freeChallenge Problems
Total Questions
2
Estimated Time
4 min
Passing Score
70%
Instructions
- Read each question carefully
- You can use hints if you need help
- Complete all questions before submitting