Spring Tutorial

In the first article we will look at how to write your first Java Spring based class. The theme of our application we are going to write in this series will be a "Popular Talent Show", so our talent show will cater to a variety of talents, and we need to cater to the performers, so we will first write an interface:
  1. public interface Performer {  
  2.       void Perform() throws PerformaceException;  
  3. }
And to ensure that something goes wrong during a performance we have:
  1. public class PerformaceException extends Exception {  
  2.       /** 
  3.        * 
  4.        */  
  5.       private static final long serialVersionUID = 3648369653354254918L;  
  6. }
Where you can give any message or information, for the time being it is empty with just a UID. So without fail we introduce the first performer who can handle at a given instance n number of spinning balls:
  1. public class Juggler implements Performer {  
  2.       private int _ballCount = 5;  
  3.       public Juggler(){  
  4.       }  
  5.       public Juggler(int ballCount){  
  6.             _ballCount = ballCount;  
  7.       }  
  8.       @Override  
  9.       public void Perform() throws PerformaceException {  
  10.             // TODO Auto-generated method stub  
  11.             System.out.println("JUGGLING " + _ballCount + " BALLS");  
  12.       }  
  13. }
As you can see we have an overloaded constructor through which I can inject the count of balls the performer can handle at a given point of time.
 
Ok, now everything seems to be ready, all we need to do is notify our Spring framework about the new performer: what we need is the XML file through which we are going to do that:
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">  
  5.       <bean id="mike" class="spring.decoded.big.awards.Juggler">  
  6.             <constructor-arg value="10" />  
  7.       </bean>  
  8. </beans> 
The above file is a Spring bean definition file where we define our beans or in plain simple words, we have defined that class Juggler should be identified with the name "Mike" so that whenever he is called upon to ask to perform, we can use this name to call him out.
Another interesting thing to note is that we can explicitly pass various counts of balls to Mike without touching the class definition, how Spring allows us to do that is by the use of: "constructor-arg" which is specified for a given bean (or class in vanilla terms).
 
So, it's time that we introduce to you the first performer for the day, "Mike":
  1. public static void main(String[] args) throws PerformaceException {    
  2.     // TODO Auto-generated method stub    
  3.     System.out.println("Starting the show....");    
  4.     ApplicationContext context = new ClassPathXmlApplicationContext("spring/decoded/big/awards/big-awards.xml");    
  5.     Performer performer = (Performer) context.getBean("mike");    
  6.     if (performer == null)    
  7.         System.out.println("Mike is missing from the show...");    
  8.     performer.Perform();    
  9. }
Right-click on your class which has the main method and select "Run As" -> "Java Application", if everything goes fine, you should see the following in the console terminal:
 
Spring.jpg
 
So that's it for the first chapter, you saw how to set a small class using a Spring container and get its instances. So of all these things what was so great about Spring? Why do so many things to invoke such a trivial method. Well the first thing to make a note of is that no where you used a keyword "new" to instantiate your performer, that was done for you by the Spring framework, which handles the object state* on its own; instead you worry about when and where to allocate (using new) an instance and when not to.
 
Note: By object state we mean, whether it needs to be a singleton object shared by all callers, or one should get a new instance every time the class or bean definition is queried for from the Spring framework.
 

Constructor Injection

 
We will cover more details about constructor injection in Spring; until now we saw:
  1. How you are spared from creating objects for your classes and delegate that work to Spring
  2. How to inject primitive values to the classes using constructor injection

In this chapter we will see how to pass reference arguments to the classes rather than passing primitive types. In our "Popular Talent Show" we saw a juggler so far. Next we have another performer who can juggle balls as well as sing, both at the same time, which is a very unique talent, so to showcase that let us write an interface first:

  1. public interface Song  
  2. {  
  3.        void Sing();  
  4. }
Next we will have a concrete implementation of this type:
  1. public class Singer implements Song  
  2. {   
  3.       private static  String[] Lines = {  
  4.             "I'm never lettin' go",  
  5.             "No, no, no, won't let go",  
  6.             "When you want it, when you need it",  
  7.             "You'll always have the best of me",  
  8.             "I can't help it, believe it",  
  9.             "You'll always get the best of me",  
  10.             "I may not always know what's right",  
  11.             "But I know I want you here tonight",  
  12.             "Gonna make this moment last for all your life",  
  13.             "Oh ya this is love and it really means so much",  
  14.             "I can tell from every touch"  
  15.       };  
  16.       @Override  
  17.       public void Sing()  
  18.       {  
  19.             for(int i = 0 ; i < Lines.length ; i++)  
  20.             {  
  21.                   System.out.println(Lines[i]);  
  22.             }  
  23.       }  

That's cool. So far, we have a favorite song who our singer would be singing, this popular song of Bryan Adams (his favorite singer) on the show along with Juggling, so let's create a class for the SingingJuggler:
  1. public class SingingJuggler extends Juggler  
  2. {  
  3.       private Song _song;  
  4.       public SingingJuggler(Song song)  
  5.       {  
  6.             super();  
  7.             _song = song;  
  8.       }  
  9.       public SingingJuggler(int beanCount, Song song){  
  10.             super(beanCount);  
  11.             _song = song;  
  12.       }  
  13.       public void Perform() throws PerformaceException  
  14.       {  
  15.             super.Perform();  
  16.             System.out.println("While singing...");             
  17.             _song.Sing();  
  18.       }  
  19. }
Great. So we have everything ready, now we need to declare them in the Spring bean definition file:
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">  
  5.       <bean id="mike" class="spring.decoded.big.awards.Juggler">  
  6.             <constructor-arg value="10" />  
  7.       </bean>  
  8.       <bean id="bestOfMe" class="spring.decoded.big.awards.Singer" />  
  9.       <bean id="john" class="spring.decoded.big.awards.SingingJuggler">  
  10.             <constructor-arg value="11" />  
  11.             <constructor-arg ref="bestOfMe"/>  
  12.       </bean>  
  13. </beans> 
As we did previously, we declared the Singer class as a bean with id "bestOfMe" to identify it and interestingly our Singing Juggler needs this bean, so we are injecting the same again through a constructor-arg but as a reference, using the "ref" attribute.

So, without further delay, let's invite our new performer to showcase his talent:

  1. public static void main(String[] args) throws PerformaceException  
  2. {  
  3.         // TODO Auto-generated method stub             
  4.         System.out.println("Starting the show....");  
  5.         Stage stage = Stage.getIstance();  
  6.         stage.SetUp();  
  7.         ApplicationContext context = new ClassPathXmlApplicationContext("spring/decoded/big/awards/big-awards.xml");  
  8.         Performer performer = (Performer)context.getBean("mike");  
  9.         if(performer == null)  
  10.               System.out.println("Mike is missing from the show...");  
  11.         performer.Perform();  
  12.         System.out.println("Moving onto next performance : ");  
  13.         performer = (Performer)context.getBean("john");  
  14.         if(performer == null)  
  15.               System.out.println("John is missing from the show...");  
  16.         performer.Perform();  
  17. }
Let's run the application to see the output in the console:
 
 
 
Great, so easy and simple, cheers and enjoy until the next chapter.
 

How to perform Setter Injections using the Spring framework

 
we will cover how to perform setter injections using the Spring framework. This is another way of resolving dependencies in your class; let's see it using a use case of how one can leverage this.
 
In our Popular Talent Show we have a new performer, Shaun, who can play any sort of instrument, so to represent that, let's write a generic instrument interface: 
  1. public interface Instrument  
  2. {  
  3.       void Play();  
  4. }

Next we need a class to represent our performer:

  1. public class Percussionist implements Performer  
  2. {  
  3.       private Instrument _instrument;       
  4.       @Override  
  5.       public void Perform() throws PerformaceException  
  6.       {  
  7.             // TODO Auto-generated method stub             
  8.             _instrument.Play();             
  9.       }  
  10.       public void setInstrument(Instrument instrument)  
  11.       {  
  12.             _instrument = instrument;  
  13.       }  
  14. }
The class represents a percussionist who plays the instrument injected to it from the setter method; well all looks good but we need the instrument which Shaun would be playing:
  1. public class Drums implements Instrument  
  2. {   
  3.       @Override  
  4.       public void Play()  
  5.       {  
  6.             // TODO Auto-generated method stub  
  7.             System.out.println("Playing Drums : ....");             
  8.       }   
  9. }
As you can see we have drums which implement the instrument interface and we need this set up in the bean configuration file, so the Spring framework can identify it:
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">   
  5.       <bean id="mike" class="spring.decoded.big.awards.Juggler">  
  6.             <constructor-arg value="10" />  
  7.       </bean>  
  8.        
  9.       <bean id="bestOfMe" class="spring.decoded.big.awards.Singer" />       
  10.       <bean id="john" class="spring.decoded.big.awards.SingingJuggler">  
  11.             <constructor-arg value="11" />  
  12.             <constructor-arg ref="bestOfMe"/>  
  13.       </bean>       
  14.       <bean id="drum" class="spring.decoded.big.awards.Drums" />  
  15.       <bean id="shaun" class="spring.decoded.big.awards.Percussionist">  
  16.             <property name="instrument" ref="drum" />  
  17.       </bean>       
  18.       <bean id="bigAwardsStage"  
  19.             class="spring.decoded.big.awards.Stage"  
  20.             factory-method="getIstance" />  
  21. </beans>
Notice that we have declared the percussionist too in the bean file, and instead of a constructor-arg attribute we have a property attribute to inject the dependency, what that bean declaration says is that:
 
"For the property whose name is instrument in the class Percussionist, set it with a reference drum declared in the bean configuration file above". Well, all we need now is to get the instance of this class and invoke the right method which is perform in this case to set the show on fire: In our PopularTalentShow.java class get these lines:
  1. public class PopularTalentShow  
  2. {   
  3.       /** 
  4.        * @param args 
  5.        * @throws PerformaceException 
  6.        */  
  7.       public static void main(String[] args) throws PerformaceException  
  8.       {  
  9.             // TODO Auto-generated method stub             
  10.             System.out.println("Starting the show....");  
  11.             
  12.             ApplicationContext context = new ClassPathXmlApplicationContext("spring/decoded/big/awards/big-awards.xml");  
  13.             Performer performer = (Performer)context.getBean("mike");  
  14.             if(!PrePerformaceChecks(performer, "Mike"))  
  15.                   return;                   
  16.             performer.Perform();             
  17.             System.out.println("Moving onto next performance : ");             
  18.   
  19.             performer = (Performer)context.getBean("john");             
  20.             if(!PrePerformaceChecks(performer, "John"))  
  21.                   return;             
  22.             performer.Perform();             
  23.             System.out.println("Moving onto next performance : ");  
  24.             performer = (Performer)context.getBean("shaun");  
  25.              
  26.             if(!PrePerformaceChecks(performer, "Shaun"))  
  27.                   return;             
  28.             performer.Perform();             
  29.       }  
  30.       private static Boolean PrePerformaceChecks(Performer performer, String performerName)  
  31.       {  
  32.             if(performer == null)  
  33.             {  
  34.                   System.out.println(performerName + " is missing from the show...");  
  35.                   return false;  
  36.             }             
  37.             return true;  
  38.       }   

Run the class and you should see it:
 

Feature of Java Spring framework

 
Here, we will look at another really useful feature from the Java Spring framework. There are occasions when you want to perform some initialization tasks in your class before the instance of it is ready to be consumed or used by anyone and also cleanup the resources of that class when done using it; as in:
  1. public class Juggler implements Performer {  
  2.       private int _ballCount = 5;  
  3.       public Juggler(){  
  4.       }  
  5.       public Juggler(int ballCount){  
  6.             _ballCount = ballCount;  
  7.       }  
  8.       public void Initialize(){  
  9.             System.out.println("Juggler: Registering in the show.");  
  10.       }  
  11.       public void Destroy(){  
  12.             System.out.println("Juggler: Signing off from the show.");  
  13.       }  
  14.       @Override  
  15.       public void Perform() throws PerformaceException {  
  16.             // TODO Auto-generated method stub  
  17.             System.out.println("JUGGLING " + _ballCount + " BALLS");  
  18.       }  

So as you notice, before any performer in the show can perform, he needs to register into the show, so that is the first most important task that he should do before he can show his talent.
 
To do that, we need to use the Initialize() method; but wait, someone needs to invoke that method to make the Juggler eligible for the show. The first possibilty that occurs to us is to either invoke that method in our main method or have a Bootstrap class which does the job of invoking the initialize methods of all the beans.
 
Such a way would be very tedious and the list of such invokes would keep increasing and hence the maintainability of such code becomes very difficult.
 
Here comes Spring again to our rescue, wherein in my bean configuration file, I can ask Spring to perform initialization of my bean once the Spring context is created, as in:
  1. <bean id="mike" class="spring.decoded.big.awards.Juggler" init-method="Initialize" destroy-method="Destroy">    
  2.             <constructor-arg value="10" />    
  3. </bean>
Notice that the init-method and destroy-method attributes specified with the bean declaration tells Spring to invoke the Initialize method of the bean once it is instantiated and destroy-method once the Spring context is closed or disposed of.
 
Let us see a working example of this. I have made changes to the PopularTalentShow::main(..) method and it should look something like this now:
  1. public static void main(String[] args) throws PerformaceException {  
  2.     // TODO Auto-generated method stub  
  3.     System.out.println("Starting the show....");  
  4.     ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/decoded/big/awards/big-awards.xml");  
  5.     Performer performer = (Performer) context.getBean("mike");  
  6.     if (!PrePerformaceChecks(performer, "Mike"))  
  7.         return;  
  8.     performer.Perform();  
  9.     System.out.println("\nMoving onto the next performance");  
  10.     performer = (Performer) context.getBean("john");  
  11.     if (!PrePerformaceChecks(performer, "John"))  
  12.         return;  
  13.     performer.Perform();  
  14.     System.out.println("\nMoving onto the next performance");  
  15.     performer = (Performer) context.getBean("shaun");  
  16.     if (!PrePerformaceChecks(performer, "Shaun"))  
  17.         return;  
  18.     performer.Perform();  
  19.     System.out.println("\nShow is over.");  
  20.     context.close();  

Notice the context.close() call which would invoke the destroy-method on all the beans specified in our bean declaration file and perform the cleanup task, now if you run the application:
 
 
Notice the initialization stuff happening in the beginning, and the cleanup being performed in the end, the hefty job being delegated to Spring with just little or no effort.
 

Inject a dependency which is a collection

 
So far we have covered the setting of the expectations of the classes using constructor injection or the setter injections, and we saw how we can set a single bean expectation. What if you want to inject a dependency which is a collection? Well, Java Spring lets you do that with collection elements of Spring:
  • <list> : Helps you setup injection of list of values, allowing duplication of values
  • <set> : Helps you setup injection of set of values, ensuring distinct (i.e. no duplication) values
  • <map> : Helps you setup injection of name-value pairs, name and value can be of any type.
  • <props> : Helps you setup injection of name-value pairs, name and value both should be of type String only.
In our "Popular Talent Show" we have a performer who can play more than one instrument at the same time so let us see how we can implement this:
  1. public class BandMan implements Performer {  
  2.       private Collection<Instrument> _instrumentList;  
  3.       public void Initialize(){  
  4.             System.out.println("One Man Band: Registering in the show.");  
  5.       }  
  6.       public void Destroy(){  
  7.             System.out.println("One Man Band: Signing off from the show.");   
  8.       }  
  9.       @Override  
  10.       public void Perform() throws PerformaceException {  
  11.             // TODO Auto-generated method stub  
  12.             for(Instrument instrument : _instrumentList){  
  13.                   instrument.Play();  
  14.             }  
  15.       }  
  16.       public void setInstruments(Collection<Instrument> instrumentList){  
  17.             _instrumentList = instrumentList;  
  18.       }  
  19. }
We have created a new class which would represent our one-man-band army. It has nothing special, just a collection set using the setter method, and in the interface implementation we iterate over the available instruments and invoke the play method on it.

Now our performer would need multiple instruments to play at the same time, so let us go ahead and create a "Flute" instrument for our performer using the "Drum" instrument that is already available:
  1. public class Flute implements Instrument {  
  2.       @Override  
  3.       public void Play() {  
  4.             // TODO Auto-generated method stub  
  5.             System.out.println("Playing Flute : ....");  
  6.       }  
  7. }
No magic so far. Next what we need is to declare our performer in the bean configuration file:
  1. <bean id="flute" class="spring.decoded.instruments.Flute">  
  2. </bean>  
  3. <bean id="edward" class="spring.decoded.talent.show.BandMan" init-method="Initialize" destroy-method="Destroy">  
  4.         <property name="instruments">  
  5.               <list>  
  6.                     <ref bean="drum"/>  
  7.                     <ref bean="guitar"/>  
  8.               </list>  
  9.         </property>  
  10. </bean>
Notice the bean declaration, that's the important place to focus on and make use of the collection elements of the Spring framework. We have used the list element and given it the references to the two beans, one drum and the other flute.
 
That's all we need to inject the list into the band man class (or bean), and we need to invoke this into the main method just as we did for other beans. Run the application and you should see something like this:
 
 
Well, this was as simple as it could be. You can play around with the other collection elements which I mentioned in the beginning of the article, you just need to change the list element to any of the other three elements and set the values appropriately. In the case of name-value pairs:
  1. <bean id="edward" class="spring.decoded.talent.show.BandMan" init-method="Initialize" destroy-method="Destroy">  
  2.     <property name="instruments">  
  3.         <map>  
  4.             <entry key="Fute" value-ref="flute" />  
  5.             <entry key="Drums" value-ref="drum" />  
  6.         </map>  
  7.     </property>  
  8. </bean> 
And the private member to hold the collection in the BandMan class should be:
  1. private Map<String, Instrument> _instrumentMap; 
It's so simple and easy, without any hassles. That is it for this article, we will see some more action in future chapters, until then enjoy.