Monday, August 10, 2020

Dependency Injection - DI

Dependency Injection is a pattern to implement IoC in which the control of injecting object dependencies is transferred to the framework.

Dependency injection can happen in the way of passing parameters to the constructor or by post-construction using setter methods.

In traditional programming:


public class Store {

    private Item item;

    public Store() {

        item = new ItemImpl1();    

    }

}



In the above example the 'Item' implementation is done in the store class itself.


In DI,


public class Store {

    private Item item;

    public Store(Item item) {

        this.item = item;

    }

}


Now, to provide the implementation of the 'Item' interface, we can follow various ways. The one below is constructor based dependency injection.


@Configuration

public class AppConfig {

    @Bean

    public Item item1() {

        return new ItemImpl1();

    }

    @Bean

    public Store store() {

        return new Store(item1());

    }

}


Types of dependency injection

1. constructor based

    when the constructor invokes a class with a number of arguments, each representing a dependency on other class

2. setter based

    calling setter methods on the beans after invoking a no-argument constructor. Use of @Required on a setter makes the setter a required dependency

we can also use a mixture of both constructor based and setter based dependency injection. The good option is to use constructor arguments for mandatory dependencies and setter for optional dependencies.


Benefits of dependency Injection

- minimizes the amount of code
- makes application easy to test
- loose coupling
- eager instantiation and lazy loading of services

No comments:

Post a Comment

Spring - AutoWiring

Spring automatically resolves the dependencies between the collaborating beans by inspecting the contents of the BeanFactory. This is called...