Inversion of Control (IoC)
Inversion of Control is a principle in software engineering which transfers the control of objects or portions of a program to a container or framework. It is more general than dependency injection.
Dependency Injection or Dependency Inversion (DI)
Dependency injection is a pattern we can use to implement IoC
IoC Container or Dependency Injection Container (DIC)
- In the Spring framework, the interface “ApplicationContext” (interface) represents the IoC container.
- The Spring container is responsible for instantiating, configuring and assembling objects known as beans, as well as managing their life cycles.
Types of dependency injection
- constructor injection
- field injection
- setter injection
- interface injection — How to implement?? java doesn’t support it??
// [Field injection]
@Autowired
private SomeService someService;// [Setter injection]
// Making sure all the dependencies are intialized is difficult
@Autowired
public void setSomeService(SomeService someService) {
this.someService = someService;
}// [Constructor injection]
// Benefit is that the dependencies are expressed explicitly
@AutoWired
public MyService(SomeService someService) {
this.someService = someService;
}
// As of Spring 4.3, classes with a single constructor can omit the @Autowired annotation.
- It is a matter of preference, but people prefer constructor injection over field injection, since constructors explicitly say what they are depending on.
- Also it might be easy to test classes with constructor injection.