Junior — Middle
In which cases is it better to use setters for dependency injection in your code?
sobes.tech AI
Answer from AI
Setter dependencies (setter injection) are better to use when:
- The dependency is not mandatory for the correct operation of the object, and it can be set later.
- There is a need to change the dependency during the object's lifecycle.
- The object is created without all dependencies, and they are added after creation (for example, during configuration).
Example: if you have a class that can work with different logger implementations, and you want to be able to change the logger without recreating the object, then setters are more suitable than a constructor.
public class Service {
private Logger logger;
public void setLogger(Logger logger) {
this.logger = logger;
}
public void doWork() {
if (logger != null) {
logger.log("Work started");
}
// ...
}
}