Junior — Middle
How can dependencies be injected through the Inversion of Control (IoC) container?
sobes.tech AI
Answer from AI
Dependency injection via Inversion of Control (IoC) container in Java is usually implemented with frameworks like Spring. Main methods of injection:
- Constructor injection — dependencies are passed through constructor parameters.
- Setter injection — dependencies are set via special methods after object creation.
- Field injection — dependencies are injected directly into class fields using annotations.
Example with Spring and annotations:
@Component
public class Service {
private final Repository repository;
@Autowired
public Service(Repository repository) {
this.repository = repository;
}
}
Here, the IoC container creates a Repository object and passes it to the Service constructor. This approach simplifies testing and dependency management.