:::: MENU ::::

Spring IoC and Dependency Injection

Spring IoC and Dependency Injection

What is Spring IOC ?

Spring IOC (Inversion Of Control) also known as Dependency Injection is basically the core part of Spring framework which is responsible for managing object lifecycles of specific objects: creating these objects, calling their initialization methods, and configuring these objects by wiring them together. Object created by the Spring Container are known as Bean. Spring IOC and Dependency injection is based on Factory Design Pattern.

Lets try to understand the dependency injection by some example code. Prerequisites for the example and Spring Dependency Injection understanding are

If you remember we used a scenario of getting interest rate for different account type in our Factory Design Pattern example, In this example also we extend the same code and modify it to use the Spring Container to generate the instance for us, and we use the Bean to achieve the same output. We wont use the “new” keyword in this example to create hard coded instance.

As we know Spring Container is based on two approach: Bean Factory and Application Context. We try them one by one, to get the same output but for basic example it won’t make much difference.

Bean Factory Approach:

Account Class:

Fixed Account : SubClass Implementing Account Interface

Saving Account : SubClass Implementing Account Interface

PPF Account : SubClass Implementing Account Interface

Account Factory Class: Using the BeanFactory to get the instance from the Spring Beanfactory Container.

Spring BeanFactory xml File:

Client Class:

Application Context Approach:
For ApplicationContext we have to change the way to load the SpringBean.xml file, and the rest of the programs are same. In short only AccountFactory will change a bit.

You can fork/clone the code from GitHub, or you can simple download the project from below link.

Download the Source Code

Download it – Spring Examples
Koushik Ghosh

Koushik Ghosh

Co-founder of CodeStrive. I am a developer in Java. I love coffee, music, coding, open source technology and playing Counter Strike. Feel free to connect me ..
Koushik Ghosh

Latest posts by Koushik Ghosh (see all)

Spring Setup
Spring AOP - Introduction
Pride that quarells at self-breath