Junior — Middle
How do dependency injection approaches via constructor and via setter differ in software development?
sobes.tech AI
Answer from AI
Dependency Injection through constructor and setter are two common approaches, each with its own features:
-
Through constructor:
- Dependencies are passed during object creation.
- Ensures immutability of dependencies after creation.
- Guarantees that the object is always in a correct state with necessary dependencies.
- Suitable for mandatory dependencies.
-
Through setter (installation method):
- Dependencies are set after object creation.
- Allows changing dependencies during the object's lifecycle.
- May lead to a state where the object is created but dependencies are not yet set (potentially incorrect operation).
- Convenient for optional dependencies or when dependencies need to be changed dynamically.
In development context:
- Constructor approach promotes creating more reliable and predictable code.
- Setters provide flexibility but require additional checks for object state correctness.
Example:
// Dependency injection via constructor
public class UserService {
private final UserRepository repo;
public UserService(UserRepository repo) {
this.repo = repo;
}
}
// Dependency injection via setter
public class UserService {
private UserRepository repo;
public void setUserRepository(UserRepository repo) {
this.repo = repo;
}
}