Sobes.tech
Middle+

What are the pitfalls of setter injection?

sobes.tech AI

Answer from AI

Setter injection has several pitfalls:

  • Optional dependency setting: if the setter is not called, the object may remain in an incorrect state.
  • Immutability issues: objects become mutable after creation, complicating data flow and testing.
  • Initialization order: it is difficult to guarantee that all dependencies are set before using the object.

Example:

public class Service {
    private Repository repo;

    public void setRepository(Repository repo) {
        this.repo = repo;
    }

    public void doWork() {
        if (repo == null) {
            throw new IllegalStateException("Repository not set");
        }
        repo.query();
    }
}

Here, if setRepository is not called, the doWork method will throw an error.