0 votes
485 views
in Spring by
What is dependency injection (DI) and types of dependency injection (DI) ?

1 Answer

0 votes
by (2.8k points)

Dependency Injection (DI):- Dependency Injection is provided by Spring IOC(Inversion of Control). The Spring-Core module is responsible for injecting dependencies through either Constructor or Setter methods. The design principle of Inversion of Control emphasizes keeping the Java classes independent of each other and the container frees them from object creation and maintenance. These classes, managed by Spring, must adhere to the standard definition of Java-Bean. Dependency Injection in Spring provides us loose-coupling between the classes.

Why needed for Dependency Injection?
We Suppose to, class One needs the object of class Two to instantiate or operate a method, then class One is said to be dependent on class Two. Now though it might appear okay to depend a module on the other but, in real world, this could lead to a lot of problems, including system failure. Hence such dependencies need to be avoided.

Spring IOC resolves such dependencies by using Dependency Injection (DI), which makes the code easier to test and reuse. Loose coupling between classes can be possible by defining interfaces for common functionality and the injector will instantiate the objects of required implementation. Task of instantiating objects is done by the container according to the configurations specified by the developer.

There are two types of Spring Dependency Injection:-

  1. Setter Dependency Injection:- In the Setter Dependency Injection, the Dependency Injection will be injected with the help of setter and/or getter methods. Now to set the Setter Dependency Injection as Setter Setter Dependency Injection in the bean, it is done through the bean-configuration file For this, the property to be set with the Setter Setter Dependency Injection is declared under the <property> tag in the bean-config file.
  2. Constructor Dependency Injection:- In the Constructor Dependency Injection, the Dependency Injection will be injected with the help of contructors. Now to set the Dependency Injection as Constructor Dependency Injection in bean, it is done through the bean-configuration file For this, the property to be set with the Constructor Dependency Injection is declared under the <constructor-arg> tag in the bean-config file.

Share:- Whatsapp Facebook Facebook


Welcome to Developerhelpway Q&A, where you can ask questions and receive answers from other members of the community.

Categories

...