Spring MVC Fast Tutorial: Dependency Injection

What are we going to build?

Use singletons of CarManager and BrandManager instead of creating multiple instances.

What is dependency injection ?

Dependency injection (also called inversion of control) is basically giving an object what it needs instead of letting this object get it by itself.

CarManager singleton for CarListController

For the moment, CarListController gets its instance of CarManager by itself:

CarManager carManager = new CarManager();

Let's change that by making it an attribute:

package springmvc.web;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
 
import springmvc.service.CarManager;
 
public class CarListController implements Controller {
	private CarManager carManager;
 
	public ModelAndView handleRequest(HttpServletRequest arg0,
			HttpServletResponse arg1) throws Exception {
 
		ModelAndView modelAndView = new ModelAndView("carList");
		modelAndView.addObject("carList", this.carManager.getCarList());
 
		return modelAndView;
	}
 
	public CarManager getCarManager() {
		return carManager;
	}
 
	public void setCarManager(CarManager carManager) {
		this.carManager = carManager;
	}
}

We now need to instantiate a CarManager somewhere else and pass it to this controller. It's done in '/WEB-INF/springmvc-servlet.xml':

<bean id="carManager" class="springmvc.service.CarManager"/>
 
<bean name="/list_cars.html" class="springmvc.web.CarListController">
  <property name="carManager" ref="carManager"/>
</bean>
  • a bean 'carManager' is created
  • it's used to initialize 'carManager' of CarListController.

We build (ant), relaunch Tomcat: http://localhost:8180/springmvc/list_cars.html

CarManager singleton for CarNewController

Do it by yourself, it's exactly the same. In the configuration file, use the CarManager instance you've already declared for '/new_car.html'.

CarManager

Since we now use a single instance of CarManager for our whole application, we don't need its carList attribute to be static anymore:

package springmvc.service;
 
import java.math.BigDecimal;
import java.util.LinkedList;
import java.util.List;
 
import springmvc.model.Brand;
import springmvc.model.Car;
 
public class CarManager {
 
	private List<Car> carList;
 
	public CarManager() {
		Brand brand1 = new Brand();
		brand1.setId((long)1);
		brand1.setName("Mercedes");
		brand1.setCountry("Germany");		
 
		Brand brand2 = new Brand();
		brand2.setId((long)2);
		brand2.setName("Peugeot");
		brand2.setCountry("France");		
 
		Car car1 = new Car();
		car1.setId((long)1);
		car1.setBrand(brand1);
		car1.setModel("SL 500");
		car1.setPrice(new BigDecimal(40000));
 
		Car car2 = new Car();
		car2.setId((long)2);
		car2.setBrand(brand2);
		car2.setModel("607");
		car2.setPrice(new BigDecimal(35000));
 
		carList = new LinkedList<Car>();
		carList.add(car1);
		carList.add(car2);	
	}
 
	public List<Car> getCarList() {
		return carList;
	}	
 
	public Car createCar(Car c) {
		Car car = new Car();
		car.setId((long)carList.size() + 1);
		car.setBrand(c.getBrand());
		car.setModel(c.getModel());
		car.setPrice(c.getPrice());
 
		carList.add(car);
 
		return car;
	}
}

BrandManager

Let's do the same for BrandManager:

  • define an instance of BrandManager in the configuration file
  • use it for CarNewController (add a private attribute, remove instantiations)
  • make its brandList attribute not static

Externalize initialization code

We can go even further: initialize carList (CarManager) and brandList (BrandManager) in Spring configuration file:

    <bean id="carManager" class="springmvc.service.CarManager">
       <property name="carList">
         <list>
           <ref bean="car1"/>
           <ref bean="car2"/>
        </list>
        </property>
    </bean>    
 
    <bean id="brandManager" class="springmvc.service.BrandManager">
      <property name="brandList">
        <list>
          <ref bean="brand1"/>
          <ref bean="brand2"/>
        </list>
      </property>
    </bean>
 
    <bean id="brand1" class="springmvc.model.Brand">
        <property name="id" value="1"/>
        <property name="name" value="Mercedes"/>
        <property name="country" value="Germany"/>
    </bean>
 
    <bean id="brand2" class="springmvc.model.Brand">
        <property name="id" value="2"/>
        <property name="name" value="Peugeot"/>
        <property name="country" value="France"/>
    </bean>
 
    <bean id="car1" class="springmvc.model.Car">
        <property name="id" value="1"/>
        <property name="brand" ref="brand1"/>
        <property name="model" value="SL 500"/>
        <property name="price" value="40000"/>
    </bean>
 
    <bean id="car2" class="springmvc.model.Car">
        <property name="id" value="2"/>
        <property name="brand" ref="brand2"/>
        <property name="model" value="607"/>
        <property name="price" value="35000"/>
    </bean>
  • we define brands
  • we define cars using the brands
  • we initialize CarManager and BrandManager lists
  • notice the difference between the 'value' attribute, where you put a primary type and 'ref', where you give a bean name.

To make it work, we just need to add a setter method for CarManager and BrandManager's lists and remove the now useless initialization code. In 'WEB-INF/src/springmvc/service/BrandManager.java':

package springmvc.service;
 
import java.util.List;
 
import springmvc.model.Brand;
 
public class BrandManager {
 
	private List<Brand> brandList;
 
	public List<Brand> getBrandList() {
		return brandList;
	}	
 
	public void setBrandList(List<Brand> brandList) {
		this.brandList = brandList;
	}
 
	public Brand getBrandById(Long id) {
		for (Brand brand : brandList) {
			if (brand.getId().equals(id))
				return brand;
		}
		return null;
	}
}

In 'WEB-INF/src/springmvc/service/CarManager.java':

package springmvc.service;
 
import java.util.List;
 
import springmvc.model.Car;
 
public class CarManager {
 
	private List<Car> carList;
 
	public List<Car> getCarList() {
		return carList;
	}	
 
	public void setCarList(List<Car> carList) {
		this.carList = carList;
	}
 
	public Car createCar(Car c) {
		Car car = new Car();
		car.setId((long)carList.size() + 1);
		car.setBrand(c.getBrand());
		car.setModel(c.getModel());
		car.setPrice(c.getPrice());
 
		carList.add(car);
 
		return car;
	}
}

Much cleaner, isn't it? :-)

We rebuild (ant), relaunch Tomcat: http://localhost:8180/springmvc/list_cars.html

Everything should still work.. You can download the project here.


Previous: Form Validation --- Up: Spring Fast Tutorial

 

Feedback

Really true and wonderful 1 Hr. work tutorial. Keep it. Cheers.
ravi
June 14, 2008
#1
this is what I am looking for.Really explained spring in easiest way.Is there ne tutorial like this for hibernate?
jaydit chitre
July 17, 2008
#2
Quick and useful. Thanks
Sharmila
July 23, 2008
#3
Thanks a ton!!... you should be a teacher ;)
Paps
July 31, 2008
#4
More useful and quick learning. Thanks
Murali Krishna Mallam
August 2, 2008
#5
very nice tutorial. a great starting point, thanks.
brian
August 3, 2008
#6
i follow spring step by step tutorial but this one is kinda simple...so use of interface is optional for IoC, and anyone have encountered this problem? Neither BindingResult nor plain target object for bean name 'command' available as request...
bryan
August 6, 2008
#7
It is Very helpful tutorial..Thanks for sharing
Aks
August 19, 2008
#8
it's very very very nice example
mohan
August 20, 2008
#9
It is very nice tutorial for beginners... Thanks.
JJ
August 22, 2008
#10
Thanks for a really simple and fun tutorial :-) Just one thing. I had to change the uri for the jstl taglib for the jsps - From - <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> To - <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
Shreekant
August 29, 2008
#11
This is a great tutorial. I can say the best tutorial I saw on the web. I really appreciate your effort.
JB
September 12, 2008
#12
Super tutorial. Thx
Selvedin
September 25, 2008
#13
I have to agree with others that this tutorial is very useful. Thank you very much.
Jan
September 26, 2008
#14
i'm really glad to see such a nice,easy and introductry tutorial.i found the tutorial usufel and helpfull. it would be nice if there would be another tutorial which covers AOP, (JSF + STRUTS+ SPRING). i hope im not asking too much
DMX
October 14, 2008
#15
Awesome.. Pretty good tutorial, which shows the power of Springs IOC. Thank You
Lak
October 16, 2008
#16
Great Tutorial! really helped me, to get an idea of spring. Thx
Markus
October 24, 2008
#17
Wonderful tutorial....very useful for guys who are new to spring frame work.... thanks alot.
sree
November 11, 2008
#18
Very precise and covering full implementation of spring frame. Great work. I expect more. If you please show integration with Hibernate.
Ratnesh
November 18, 2008
#19
Really too good... Earlier I was not knowing even ABC of Spring... After this I have quit a good knowledge of Spring MVC flow.
Praveen
November 21, 2008
#20
Nice!!!!! Thanks
Chetan
December 1, 2008
#21
Really fantastic
Abdul
December 1, 2008
#22
Really awesome, material was very succint
Rad
January 6, 2009
#23
Thanks, Great tutorial for newcomer to spring-mvc module.
Anant
January 7, 2009
#24
Great Job, I really appreciate it since it give me very well understanding of how to build and how it works. Really Really Great Tutorial!!!
awayyout
January 21, 2009
#25
simple and great.. thanks a lot..
Siri
January 22, 2009
#26
Thanks for this great tutorial Jérome! Outstanding!!
Carlos
February 8, 2009
#27
Simply Superb, Great Job and Thanks alot!
Kala...
March 20, 2009
#28
that's all i can want from tutorial.
mehdi
March 24, 2009
#29
Thank you so much for this! this is like an epiphany article amongst all others. is there something like this for spring-hibernate? thanks again
leithold
March 30, 2009
#30
its Really superb. Thank U Very Very Much.
Dhaval Vekaria
April 10, 2009
#31
Me too joining the club. Pretty simple,nice and clear tutorial for Spring MVC for starters
Rohit
April 15, 2009
#32
Big hand to you, Sir! I'm a Spring newbie and this tutorial put me right back on track. Respect!
Ville
April 19, 2009
#33
Its really a good one to understand what spring does and mainly what Dependency injection is. Thanks to the Author.
Dhami
April 21, 2009
#34
Good work, thanks!
Boden
April 21, 2009
#35
nice tutorial
shishir saxena
May 6, 2009
#36
Indeed this is a wonderful and neat explained tutorial
mma
May 6, 2009
#37
very use full information for spring begineers,if it is possible provide advance spring example.
venkanna india
May 14, 2009
#38
You have explained spring in way that any one can easily understand it. Thanks, Tejash <a href="http://technical-tejash.blogspot.com">Technical Details By Tejash</a>
Tejash
May 15, 2009
#39
Great job !! Keep it up !!!!
Praveen
May 17, 2009
#40
Awesome tutorial .. keeps simple things simple .. the way i like it :)
srimal
May 19, 2009
#41
Exexllent work
nav
May 19, 2009
#42
Its very easy to understand for the begineers, thanks very much
Kish
May 28, 2009
#43
Simple and neat
Nitin
May 31, 2009
#44
Thanks - this is exactly what you need as the first step into any new technology.
Barry
June 11, 2009
#45
Good one
tt
June 12, 2009
#46
yey!
er
June 12, 2009
#47
This is wonderful tutorial all the way...
Murthy
June 22, 2009
#48
Bravo !!! Magnifico !!! Merci !!!
Paco
June 23, 2009
#49
Thanks...this helps me a lot
Piyush
June 26, 2009
#50
Really Nice...:)
Spring lover
July 8, 2009
#51
Yeah its Great...
Nitin Sindhwani
July 13, 2009
#52
Indeed great work which helped me to get started with Spring
Ajay Sahani
July 14, 2009
#53
The best for beginners....Thanks a lot
Jagruti
July 18, 2009
#54
Maybe better than the official Spring sample ! Is help me understand how to use the -servlet.xml file and how to configure the form beans. Very helpful sample, great job.
sangoman
July 21, 2009
#55
Great work Buddy...Thank a lot
Srinivas
July 21, 2009
#56
Hmm wt to say but this "Excellent Job dude".As requested by many, plz gift us a tutorial on hibernate also...Expecting it soon :P
mac
July 23, 2009
#57
Just the right tutorial for a programmer having kids in tow! Good work!
http://economics-science-life.blogspot.com/
July 25, 2009
#58
very good material

July 30, 2009
#59
This tutorial is called "Simply Superb...!"
Bobby
August 4, 2009
#60
good stuff. easy to follow but very informative
whistler
August 11, 2009
#61
certainly the fastest and most understandable tutorial available on the internet!
Shashank Araokar
August 13, 2009
#62
Short and sweet and to the point. Thanks a lot for putting this up.
Rex
August 14, 2009
#63
very good tutorial
sindhu
August 17, 2009
#64
nice one
punitha
August 17, 2009
#65
Is fantastic one,I have admired the way of presentation,Thanks a lot,for provide this material,I hope this should very very useful to all kinds of folks.We are expecting more.. will you ?
Sriranjani
August 19, 2009
#66
very good one.can u just have one more wid hibernate..i know u can do it very easily :)
Swapnil
August 20, 2009
#67
Thanks a lot.. This was very very helpful. In fact was just going thru this tutorial and got a very nice nice insight of the flow used in Spring MVC. Keep posting such nice and simple tutorials.
Sai Saran
August 21, 2009
#68
very good one.
chhaya
August 26, 2009
#69
Excellent! Very useful
vivek
August 31, 2009
#70
Excellent Work. If you know MVC. If you have worked on any MVC frameworks like struts... this is all you need to get to know Spring MVC. Good job.
Kanu_D
September 1, 2009
#71
nice one those who know spring before it will be an nice example to brush up.... nice work keep it up...
Elayaraja.D
September 2, 2009
#72
Thanks, excellent work. Best tutorial I have ever seen. If you can write a book with the same clarity and simplicity, you'll be a rock start in Java and Spring!
Rolf
September 2, 2009
#73
^^ that would be a "rock start" ... sorry for typo!
Rolf
September 2, 2009
#74
^^ um, rock star ... rock star ... rock star ... DOH! (autocorrect???)
Rolf
September 2, 2009
#75
Thanks a lot for putting this up. I wish I could also put something so clear and so helpful thing. Thanks a lot once again.
Ajay
September 11, 2009
#76
A+ :)

September 17, 2009
#77
Wow gr8 command..
Ashutosh
October 6, 2009
#78
Very Good and precise tutorial
Avneesh Saini, Noida
October 6, 2009
#79
good tutorial
Subash
October 9, 2009
#80
Simple and Good
Kiran Rayilla
October 11, 2009
#81
Very ... very super good!!! The best tutorial for spring_WEB_mvc! Do you have this for Portlet spring_PORTLET_mvc ? (Becuase nowaday WebPortal/Porlet-Application is in comming!)
x123
October 16, 2009
#82
very good tutorial. Explained in east steps. And best thing is that the code works too :)).
kaushik666
October 21, 2009
#83
U should put for DAO & Transaction Mgmt. anyways thanks for this...

November 1, 2009
#84
Its very crispy and altogether useful--good piece of work.
anand
November 5, 2009
#85
No confusions. Crystal clear tutorial. An example to other online tutorials. To the point explanation. First of all, the (simple)directory structure should be explained instead of giving vague explanations/definitions. You did it.
sridhar dhantu
November 10, 2009
#86
Extremely useful.

November 12, 2009
#87
Fantastic job.

November 12, 2009
#88
Excellent Work. Really Fast and very Clean. Thanks.
PC
November 12, 2009
#89
Superb!!!..Excellent work...very useful tutorial for beginners
shamel..palli
November 21, 2009
#90
Usefull one. Thanks to the Creator.
Venkatesh
November 23, 2009
#91
Thanks a lot. Very useful and easy to understand. It'll be nice if you can explain the code further.
Eurocenter
November 24, 2009
#92
good tutorial...
anutwalidera
December 2, 2009
#93
Thank you It's the best tutorial i ever read !!!! Thank you Mr really
sabri boubaker
December 15, 2009
#94
Best tutorial for Spring...

December 16, 2009
#95
Thank you so much! Would have never been able to grasp SpringMVC without this. Excellent work, mate.
binarycodes
December 17, 2009
#96
Thanks,,it's very superb....
Budi Syidiq
December 18, 2009
#97
awesome
Harish
December 22, 2009
#98
Thanks, Great tutorial for newcomer to spring-mvc module.
Ravi Varnapoora
December 28, 2009
#99
Very precise and covering full implementation of spring frame. Great work. I expect more. If you please show integration with Hibernate.
Sibi Varnapoora
December 28, 2009
#100
Excellent tutorial with good explanation on IoC
Radha
January 7, 2010
#101
Well prepared and excellent one.
Rajan
January 9, 2010
#102
thanks a lot for giving a excellent doc for spring.
anand
January 12, 2010
#103
Simply Great!
Jay
January 12, 2010
#104
Its a great job, done simply.
Swap
January 18, 2010
#105
Thanks for this. The final permissions I ended up setting to get out of trouble were:
        grant codeBase "file:/projects/java/spikes/springmvc/-" {
       permission java.lang.RuntimePermission "getClassLoader";
       permission java.lang.RuntimePermission "accessDeclaredMembers";
};

   
Anders Thøgersen
January 19, 2010
#106
Adipoli
Manoj
January 24, 2010
#107
Nice tutorial for the beginners. Good work keep going . . .
Karthik Dhamodharan
February 1, 2010
#108
Nice tutorial for the beginners. Good work keep going . . .
Karthik Dhamodharan
February 1, 2010
#109
Nice tutorial for the beginners. Good work keep going . . .
Karthik Dhamodharan
February 1, 2010
#110
Nice tutorial for the beginners. Good work keep going . . .
Karthik Dhamodharan
February 1, 2010
#111
I always end up having one or the other problem with the tutorials. This tutorial stands out. Many thanks for providing this.
Mahadev Semwal
February 1, 2010
#112
Great
Rama
February 15, 2010
#113
Great job
Bonzo
February 16, 2010
#114
Very simple and understandable tutorial for beginners. Thanks for sharing it :)

Could you also share it with annotation also? That would be great!
irfan
February 20, 2010
#115
Very good tutorial. It helped me lot. Thanks.
Anil
February 22, 2010
#116
Thanks for the crisp tutorial.
Subhash
February 26, 2010
#117
Nice tutorial!!!!! Thanks
Narender
February 26, 2010
#118
Excellent Tutorial.....This tutorial very useful to learn spring frame work easily.
RAJULA
February 28, 2010
#119
Nice one! This is all I needed!
Dips
March 5, 2010
#120