What is Dependency Injection
Thursday, May 20, 2010
Dependency Injection forms the core of Spring and it is very important to understand this concept if you want to learn Spring. I have seen many people who work on Spring but do not understand this concept thoroughly though the concept is really simple. The reason most people do not understand this is they start working on a readymade infrastructure defined for the project and make the changes in the configuration files mechanically.
However when we understand a concept it provides a great advantange because the architecture becomes clear and there are less chances and error as well as code becomes easier to debug. It also make it easier to work on code developed by other developers.
So what is Dependency Injection?
All the container managed classes in Spring are called bean. Simply stating, it means all the Beans (Classes) on which a bean depends on, is supplied by the container either via constructor argument or using the setter methods.
For example, if a Bean A is dependent on Bean B and Bean C, which may be an interface or a class, what happens is Spring container first creates the Bean A and depending on how or what configuration is mentioned, injects or in simple term, sets the appropriate dependency values in the Bean A by creating appropriate instance of Bean B. Bean A may be supplied the instances of Bean B & C either via constructor or using the setter methods on the Bean A.
How is Dependency Injection Beneficial?
Injecting the dependency at the runtime, makes it very flexible and promotes loose coupling. A class need not know about the dependency's implementation details and it becomes easier to change a dependency class without the need to change the dependent class code. This makes the application very flexible and robust.
0 comments:
Post a Comment