0
0
Spring Bootframework~5 mins

Field injection and why to avoid it in Spring Boot - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is field injection in Spring Boot?
Field injection is when dependencies are injected directly into class fields using annotations like @Autowired on private variables.
Click to reveal answer
beginner
Why is field injection discouraged in Spring Boot?
Field injection hides dependencies, makes testing harder, and breaks immutability because fields are set after object creation.
Click to reveal answer
beginner
What is a better alternative to field injection?
Constructor injection is better because it makes dependencies explicit, supports immutability, and improves testability.
Click to reveal answer
intermediate
How does field injection affect unit testing?
Field injection makes it hard to provide mock dependencies in tests because fields are private and set by the framework after object creation.
Click to reveal answer
beginner
What is one real-life analogy for field injection drawbacks?
It's like getting ingredients for a recipe delivered inside the cooking pot after you start cooking, making it hard to prepare and test the recipe properly.
Click to reveal answer
Which annotation is commonly used for field injection in Spring Boot?
A@Service
B@Component
C@Autowired
D@Bean
Why is constructor injection preferred over field injection?
AIt only works with private fields
BIt makes dependencies explicit and supports immutability
CIt requires less code
DIt hides dependencies
What problem does field injection cause for unit testing?
ADependencies are private and set after object creation, making mocks hard
BIt makes tests run slower
CIt requires XML configuration
DIt disables Spring context
Which of these is NOT a reason to avoid field injection?
AIt makes dependencies explicit
BIt breaks immutability
CIt complicates testing
DIt hides dependencies
What is a simple way to fix field injection issues?
AUse setter injection only
BUse static fields
CRemove all annotations
DUse constructor injection instead
Explain what field injection is and why it is generally discouraged in Spring Boot.
Think about how dependencies are set and how that affects testing and design.
You got /5 concepts.
    Describe the benefits of constructor injection compared to field injection.
    Constructor injection makes dependencies clear from the start.
    You got /4 concepts.