Sobes.tech
Middle

What types of dependency injection exist?

sobes.tech AI

Answer from AI

There are three main types of dependency injection in Java:

  1. Constructor Injection: Dependencies are passed to the object at creation through constructor parameters. This is the most recommended approach as it guarantees the presence of all necessary dependencies at object creation and makes it immutable.

    // Example of constructor injection
    public class Service {
        private final Repository repository;
    
        public Service(Repository repository) {
            this.repository = repository; // Dependency is passed through constructor
        }
    
        // ... methods using repository
    }
    
  2. Setter Injection: Dependencies are provided to the object after its creation via setter methods. This approach makes objects mutable but can be useful for optional dependencies or when object creation requires multiple initialization steps.

    // Example of setter injection
    public class Service {
        private Repository repository;
    
        public void setRepository(Repository repository) {
            this.repository = repository; // Dependency is passed through setter
        }
    
        // ... methods using repository
    }
    
  3. Field/Attribute Injection: Dependencies are injected directly into class fields. Often used with IoC frameworks that use reflection to assign values to fields annotated, for example, with @Autowired. This approach is the simplest to write but makes the code less testable without a framework and hides dependencies.

    // Example of field injection (using Spring @Autowired)
    public class Service {
        // @Autowired indicates to the framework to inject the Repository dependency into this field
        @Autowired
        private Repository repository;
    
        // ... methods using repository
    }
    

Brief comparison:

Injection Type Advantages Disadvantages
Constructor Guarantees dependencies, object is immutable, high testability Can lead to constructor bloating with many dependencies
Setter Suitable for optional dependencies, flexible Object is mutable, need to check dependencies before use
Field/Attribute Easy to write Poor testability without framework, hides dependencies