1.

What is Dependency Injection? What are the types of Dependency Injection?

Answer»

Dependency Injection (DI) is a pattern that implements Inversion of Control, removing the dependency from the code and instead have the framework or container deal with it. Dependency Injection makes code loosely coupled, which makes the application EASY to manage and test.

A typical Java application is composed of several objects that collaborate with each other to execute business logic. Traditionally each object is responsible for obtaining its own REFERENCE to the dependent objects. For example, a Service class will depend on the DAO class to get data from the database. Service class would directly create an instance of DAO class by using code like “new DAO()”. This introduces tight coupling between Service and DAO classes. This is where the Spring framework comes into rescue by removing tight coupling between the classes. In the above example, the Spring framework would inject a DAO object into Service class. This also allows us to replace the existing Database with another as and when required with minimal code changes.

Dependency Injection provides dependencies to objects at run time rather than compile time, hence making them loosely coupled. Using this concept PROGRAMMER does not create objects directly but describes how they should be created. The Code doesn’t need to connect the components and services together but just describe which services are needed by which components. Spring container will then hook them up.

Spring framework provides two mechanisms for dependency injection:

  • Constructor Based: It is implemented when a constructor of the class is defined with a number of arguments each representing a dependency on other class. The Spring container will inject the dependencies while invoking the class constructor at start-up.
  • Setter Based: It is implemented when a setter method is created for the dependency of the other class, HOWEVER, this method needs to be invoked explicitly.


Discussion

No Comment Found