3. Inversion of Control (IoC)
Let’s now focus on the concept of Inversion of Control (IoC) used by Spring to configure applications. To illustrate this concept, let’s return to the architecture of our previous test application:
![]() |
To access data from the DBMS, the test class must use the services of an object implementing the [IArticlesDao] interface, for example, an object of type [ArticlesDaoPlainODBC]. We have examined two possible solutions for instantiating such an object:
- In the first solution, the test class itself requested the instantiation of an object of type [ArticlesDaoPlainODBC]:
<TestFixture()> _
Public Class NunitTestArticlesDaoPlainOdbc
' the object under test
Private articlesDao As IArticlesDao
<SetUp()> _
Public Sub init()
' Create an instance of the object under test
articlesDao = New ArticlesDaoPlainODBC("odbc-firebird-articles", "SYSDBA", "masterkey")
End Sub
...
End Class
There is a hard-coded dependency on the class name in the code. If the class implementing the [IArticlesDao] interface were to change, the code in the [init] method would need to be modified. The following relationships exist between the objects:
![]() |
The [NunitTestArticlesDaoPlainOdbc] class takes the initiative to create the [ArticlesDaoPlainODBC] object it needs. Returning to the term "inversion of control," we can say that it is the one that has "control" over creating the object it needs.
- The second solution takes a different approach. The test class has become the following:
<TestFixture()> _
Public Class NunitSpringTestArticlesDaoPlainOdbc
'the object under test'
Private articlesDao As IArticlesDao
<SetUp()> _
Public Sub init()
' Get an instance of the Spring object factory
Dim factory As XmlObjectFactory = New XmlObjectFactory(New FileStream("spring-config-plainodbc.xml", FileMode.Open))
' Request instantiation of the ArticlesDao object
articlesDao = CType(factory.GetObject("articlesdao"), IArticlesDao)
End Sub
...
End Class
This mechanism could be summarized as follows:
![]() |
Here, the test class does not take the initiative to request the creation of an [ArticlesDaoPlainODBC] object. It simply asks Spring for a reference to such an object. If the object exists, Spring returns a reference to it. If it does not exist, Spring creates it. The test class has lost control over the creation of the [ArticlesDaoPlainODBC] object. It simply requests a reference to this object. This request will force Spring to create the object in this case. However, in another context, one could imagine that the requested object has already been created at the application’s request. Spring then does not recreate the object but returns a reference to the existing object (singleton). The concept of Inversion of Control (IoC) means here:
- that the application never takes the initiative to create the singletons it needs. It simply requests references to them.
- It is Spring that decides to create a singleton upon the first request for a reference to it


