Spring – Understanding Inversion of Control with Example
Spring IoC (Inversion of Control) Container is the core of Spring Framework. It creates the objects, configures and assembles their dependencies, manages their entire life cycle. The Container uses Dependency Injection(DI) to manage the components that make up the application. It gets the information about the objects from a configuration file(XML) or Java Code or Java Annotations and Java POJO class. These objects are called Beans. Since the Controlling of Java objects and their lifecycle is not done by the developers, hence the name Inversion Of Control.
There are 2 types of IoC containers:
That means if you want to use an IoC container in spring whether we need to use a BeanFactory or ApplicationContext. The BeanFactory is the most basic version of IoC containers, and the ApplicationContext extends the features of BeanFactory. The followings are some of the main features of Spring IoC,
- Creating Object for us,
- Managing our objects,
- Helping our application to be configurable,
- Managing dependencies
Implementation: So now let’s understand what is IoC in Spring with an example. Suppose we have one interface named Sim and it has some abstract methods calling() and data().
Now we have created another two classes Airtel and Jio which implement the Sim interface and override the interface methods.
So let’s now call these methods inside the main method. So by implementing the Run time polymorphism concept we can do something like this
But what happens if in the future another new Sim Vodafone came and we need to change again to the child class name in the code, like this
Sim sim = new Vodafone();
So we have to do our configuration in the source code. So how to make it configurable? We don’t want to touch the source code of this. The source code should be constant. And how can we make it? Here Spring IoC comes into the picture. So in this example, we are going to use ApplicationContext to implement an IoC container. First, we have to create an XML file and name the file as “beans.xml“.
Example: beans.xml File
Output Explanation: In the beans.xml file, we have created beans. So inside the id, we have to pass the unique id and inside the class, we have to pass the Class name for which you want to create the bean. Later on, inside the main method, we can tweek it out that will be described in the upcoming program.
Bean Definition: In Spring, the objects that form the backbone of your application and that are managed by the Spring IoC container are called beans. A bean is an object that is instantiated, assembled, and otherwise managed by a Spring IoC container.
Jio Calling Jio Data
And now if you want to use the Airtel sim so you have to change only inside the beans.xml file. The main method is going to be the same.
<bean id="sim" class="Airtel"></bean>
Airtel Calling Airtel Data