Dependency injection

Dependency Inversion Principle (DIP) states that two modules should not be tightly coupled with each other. Modules without dependency are very difficult to find. As we cannot avoid dependency every time, DIP states that instead of writing tightly coupled classes, the developer should write the modules using abstraction. Abstraction helps in hiding the detailing, and it exposes the functionality, so one can use them. DIP helps in ensuring loosely coupled modular programming. Dependency injection (DI) is the implementation of DIP. To know what dependency injection is, we will first have to clearly understand what a dependency is?

The state of an object is given by the values of its data members. These data members, as we all are aware, can be of primitive or secondary type. If the data members are primitive, they get their values directly, and in secondary data type, the value is dependent on state of that object. This means that whenever an object initialization happens, the data member initialization plays a very important role. In other words, we can say the data members are the dependency in object initialization. To insert or set the values of the dependency onto the object is dependency injection.

Dependency injection helps us in achieving loosely coupled architecture. Loose coupling helps us in easy testing of the modules. The code and the values it uses are separated, and can be controlled by a central configuration, which makes for easy code maintenance. The code remains unaffected, as the values are in an external configuration, making it easy to migrate with minimum changes.

In the Spring framework, dependency injection can be achieved using the following two ways:

  • Setter injection
  • Constructor injection

The preceding two injections are the ways we can use for DI, but these can be achieved in a number of ways, which are as follows:

  • XML-based configuration
  • XML-based configuration with a p namespace
  • Annotation-based configuration

So, let's start exploring them one by one.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.80.122