91-9990449935 0120-4256464 |
Dependency Injection in SpringDependency Injection (DI) is a design pattern that removes the dependency from the programming code so that it can be easy to manage and test the application. Dependency Injection makes our programming code loosely coupled. To understand the DI better, Let's understand the Dependency Lookup (DL) first: Dependency LookupThe Dependency Lookup is an approach where we get the resource after demand. There can be various ways to get the resource for example: In such way, we get the resource(instance of A class) directly by new keyword. Another way is factory method: This way, we get the resource (instance of A class) by calling the static factory method getA(). Alternatively, we can get the resource by JNDI (Java Naming Directory Interface) as: There can be various ways to get the resource to obtain the resource. Let's see the problem in this approach. Problems of Dependency LookupThere are mainly two problems of dependency lookup.
Dependency InjectionThe Dependency Injection is a design pattern that removes the dependency of the programs. In such case we provide the information from the external source such as XML file. It makes our code loosely coupled and easier for testing. In such case we write the code as: In such case, instance of Address class is provided by external souce such as XML file either by constructor or setter method. Two ways to perform Dependency Injection in Spring frameworkSpring framework provides two ways to inject dependency
Upcoming topics in Spring Dependency InjectionDependency Injection by constructorLet's see how we can inject dependency by constructor. Dependency Injection by setter method Let's see how we can inject dependency by setter method. |