DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring IoC Tutorial

Spring IoC Tutorial

Meyyappan Muthuraman user avatar by
Meyyappan Muthuraman
·
Jun. 14, 12 · Tutorial
Like (2)
Save
Tweet
Share
125.50K Views

Join the DZone community and get the full member experience.

Join For Free

in spring, the inversion of control (ioc) principle is implemented using the dependency injection (di) design pattern. let's understand dependency injection with the help of an example. first we will see a java version of the example and later we will add spring functionalities to it. as far as the example go, its pretty simple. the quizmater interface exposes the popquestion() method. to keep things simple, our quizmaster will generate only one question.

quizmaster.java
----------------
package com.vaannila;

public interface quizmaster {

	public string popquestion();
}

the strutsquizmaster and the springquizmaster class implements quizmaster interface and they generate questions related to struts and spring respectively.

strutsquizmaster.java
----------------------
package com.vaannila;

public class strutsquizmaster implements quizmaster {

    @override
    public string popquestion() {
        return "are you new to struts?";
    }

}
springquizmaster.java
----------------------
package com.vaannila;

public class springquizmaster implements quizmaster {

    @override
    public string popquestion() {
        return "are you new to spring?";
    }

}

we have a quizmasterservice class that displays the question to the user. the quizmasterservice class holds reference to the quizmaster .

quizmasterservice.java
-----------------------
package com.vaannila;

public class quizmasterservice {

    private quizmaster quizmaster = new springquizmaster();
    
    public void askquestion()
    {
        system.out.println(quizmaster.popquestion());
    }
}

finally we create the quizprogram class to conduct quiz.

quizprogram.java
----------------
package com.vaannila;

public class quizprogram {

    public static void main(string[] args) {
        quizmasterservice quizmasterservice = new quizmasterservice();
        quizmasterservice.askquestion();
    }

}

as you can see it is pretty simple, here we create an instance of the quizmasterservice class and call the askquestion() method. when you run the program as expected " are you new to spring? " gets printed in the console.

let's have a look at the class diagram of this example. the green arrows indicate generalization and the blue arrows indicates association.

as you can see this architecture is tightly coupled. we create an instance of the quizmaster in the quizmasterservice class in the following way.

private quizmaster quizmaster = new springquizmaster();

to make our quiz master struts genius we need to make modifications to the quizmasterservice class like this.

private quizmaster quizmaster = new strutsquizmaster();

so it is tightly coupled. now lets see how we can avoid this by using the dependency injection design pattern. the spring framework provides prowerful container to manage the components. the container is based on the inversion of control (ioc) principle and can be implemented by using the dependency injection (di) design pattern. here the component only needs to choose a way to accept the resources and the container will deliver the resource to the components.

in this example instead of we, directly creating an object of the quizmaster bean in the quizmasterservice class, we make use of the container to do this job for us. instead of hard coding any values we will allow the container to inject the required dependancies.

we can inject the dependancies using the setter or constructor injection. here we will see how we can do this using the setter injection.

quizmasterservice.java
-----------------------
package com.vaannila;

public class quizmasterservice {

    quizmaster quizmaster;
    
    public void setquizmaster(quizmaster quizmaster) {
        this.quizmaster = quizmaster;
    }
    
    public void askquestion()
    {
        system.out.println(quizmaster.popquestion());
    }
}

the value for the quizmaster will be set using the setquizmaster() method. the quizmaster object is never instantiated in the quizmasterservice class, but still we access it. usually this will throw a nullpointerexception, but here the container will instantiate the object for us, so it works fine.

after making all the changes, the class diagram of the example look like this.

the container comes into picture and it helps in injecting the dependancies.

the bean configuration is done in the beans.xml file.

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
xsi:schemalocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="springquizmaster" class="com.vaannila.springquizmaster"></bean>
    <bean id="strutsquizmaster" class="com.vaannila.strutsquizmaster"></bean>
    <bean id="quizmasterservice" class="com.vaannila.quizmasterservice">
        <property name="quizmaster">
        <ref local="springquizmaster"/>
        </property>
    </bean>

</beans>

we define each bean using the bean tag. the id attribute of the bean tag gives a logical name to the bean and the class attribute represents the actual bean class. the property tag is used to refer the property of the bean. to inject a bean using the setter injection you need to use the ref tag.

here a reference of springquizmaster is injected to the quizmaster bean. when we execute this example, " are you new to spring? " gets printed in the console.

to make our quizmaster ask questions related to struts, the only change we need to do is, to change the bean reference in the ref tag.

<bean id="quizmasterservice" class="com.vaannila.quizmasterservice">
    <property name="quizmaster">
        <ref local="strutsquizmaster"/>
    </property>
</bean>

in this way the dependency injection helps in reducing the coupling between the components.

to execute this example add the following jar files to the classpath.

antlr-runtime-3.0
commons-logging-1.0.4
org.springframework.asm-3.0.0.m3
org.springframework.beans-3.0.0.m3
org.springframework.context-3.0.0.m3
org.springframework.context.support-3.0.0.m3
org.springframework.core-3.0.0.m3
org.springframework.expression-3.0.0.m3

you can download and try the di example by clicking the download link below.

source: download

source + lib: download

Spring Framework Dependency injection

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • The 5 Books You Absolutely Must Read as an Engineering Manager
  • Create a REST API in C# Using ChatGPT
  • Required Knowledge To Pass AWS Certified Solutions Architect — Professional Exam
  • 10 Best Ways to Level Up as a Developer

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: