What Is Dependency Injection?
Imagine two Java classes: A and B. An object of class A has a private method that has a reference to an instance of B. Normally, you must construct A and then pass in a constructed instance of B programmatically. You can do the latter in two ways:
- As a constructor parameter in A
- Dynamic creation in the constructor of A
The two classes A and B are said to be collaborators; and, in the parlance of Spring, A has a dependency on B. This all sounds very abstract, so to help make it concrete Listing 1 illustrates the way this is typically recorded in XML in what's called a context file (more on this later).
Listing 1 A basic dependency injection.
<beans> <bean id="objectA" class="NAME OF IMPLEMENTING CLASS"> <property name="dependency"> <value>objectB</value> </property> </bean> </beans>
Don't worry about the details in Listing 1; I'll just get you started with the concepts. Spring creates beans (as in the <beans> section of Listing 1) that become available to your code on startup. So, in Listing 1, your code will be able to access an object called objectA. This is because the Spring container sorts out all the dependencies and presents your code with ready-to-use objects. Also in Listing 1, you can see the class that implements the objectA bean (I haven't included this, but I will in a later example) as well the associated property (in this case, objectB).