Is it possible to inject dependencies not only through the constructor?
sobes.tech AI
Answer from AI
Yes, it is possible. Besides constructor-based dependency injection, the following are the main methods in the Spring Framework:
-
Setter-based dependency injection: Dependencies are injected through public setter methods.
public class MyClass { private Dependency dependency; public void setDependency(Dependency dependency) { this.dependency = dependency; } // ... other methods } -
Field-based dependency injection: Dependencies are injected directly into the class fields using annotations (e.g.,
@Autowired). This method is the most common but has its drawbacks (e.g., difficulty in unit testing and hidden dependencies).public class MyClass { @Autowired private Dependency dependency; // ... other methods } -
Method-based dependency injection: A less common method where dependencies are injected through any method annotated appropriately (
@Autowired).public class MyClass { private Dependency dependency; @Autowired public void configure(Dependency dependency) { this.dependency = dependency; } // ... other methods }
The choice of method depends on the specific situation and preferences. Constructor injection is generally considered preferable because it guarantees that the object will be created with all necessary dependencies and simplifies testing. However, field or setter injection can be more convenient for optional dependencies or when working with legacy code.