What common mistaken approaches to dependency injection in Spring do you know?
sobes.tech AI
Answer from AI
Common mistakes when implementing dependencies in Spring:
-
Using
newto create dependencies instead of injecting through Spring — leads to losing DI benefits and testing difficulties. -
Lack of annotations or incorrect usage (
@Autowired,@Component,@Service), which prevents Spring from finding or injecting the required bean. -
Injecting dependencies through fields without using constructors or setters — complicates testing and violates encapsulation.
-
Cyclic dependencies, where two beans depend on each other directly, causing errors during context creation.
-
Using
@Autowiredwithout specifying optionality (required=false), which can lead to errors if the bean is not found. -
Injecting too many dependencies into a single class, indicating a violation of the single responsibility principle.
The correct approach is to use constructor injection, annotate classes and dependencies, avoid manual object creation, and monitor the application's architecture.