ioc container

Showing posts with label ioc container. Show all posts
Showing posts with label ioc container. Show all posts

Dependency injection in Spring Boot


Dependency injection


What is Dependency injection?

  • Dependency injection is a form of the IoC container
  • It is just passing dependencies to other objects or frameworks.
  • Dependency injection allows you to remove hardcoded dependencies and make applications loosely coupled, extendable and maintainable.
  • In Spring it uses two types of dependency injection methods, constructor and setter injection. In addition, we can use field injection as well.

Constructor injection

private final Flavor flavor;

Cake(Flavor flavor) {
    Objects.requireNonNull(flavor);
    this.flavor = flavor;
}
  • If there is a single construction, @Autowired annotation is optional after Spring 4.3. But if there is more than one constructor, we need to specify the constructor by mentioning it using @Autowired annotation.
  • Autowired field should be final
  • This method is immutable and reliable

Setter injection

private Topping toppings;

@Autowired
void setTopping(Topping toppings) {
    this.toppings = toppings;
}
  • More flexible
  • Objects are mutable
  • Null checks are required
  • Less secure than constructor injection, because dependencies can be overridden

Field injection

@Autowired
private Topping toppings;

  • Very easy to use, but not recommended. 
  • If you use this, the unit tests can be failed.

When to use Setter or Constructor injections

  • Constructor injection is better than Setter injection.
  • Use Setter injection when a number of dependencies are more or you need readability.
  • Use Constructor Injection when Object must be created with all of its dependencies.
  • We can change a value easily when using the setter injection. It is more flexible than constructor injection.
  • Setter injection will override the constructor injection. If we use both setter and constructor injection, the IOC container will use setter injection.

Why does constructor injection better than others?

  • All required dependencies are available at the initialization time.
  • This is very important in writing unit tests. Because it forces to load all objects for all dependencies.

Advantages of dependency injection

  • Easy unit testing
  • Configurable components
  • Separations of concerns
  • More control