Sobes.tech
Junior — Middle

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 new to 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 @Autowired without 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.

What common mistaken approaches to dependency… - sobes.tech