Published on

This would be helpful for a beginner

Published in: Education, Technology, Sports
1 Comment
1 Like
No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide


  1. 1. Beginning of Spring<br />Part - 1<br />Author: <br />Santosh Kumar Kar<br />santosh.bsil@yahoo.co.in<br />
  2. 2. Who This Tutor Is For?<br />This tutor is for them who just start learning Springs. After going through this session, you will have the basic understandings of Spring Framework. You will able to write small applications using Spring. Also you can understand other complicated Spring projects after going through this session.<br />I would suggest you to refer other good Spring books and tutors to understand Springs in depth. Remember, you can understand only the basics of Springs through this tutor which will be helpful to go depth into Springs. <br />You can also download the source code of the examples from Download Links available at http://springs-download.blogspot.com/<br />Good Luck…<br />Santosh<br />
  3. 3. Introduction:<br />In many books or sites, you will find about Spring that Spring supports inversion of control (IOC) and that it is a lightweight framework. You might be confused, what is inversion of control (IOC)? What is the purpose of using IOC? Why this feature is desirable?<br />
  4. 4. Course Contents<br /><ul><li>The confused word: IOC
  5. 5. Understanding ApplicationContextand method getBean("<BEAN NAME>")
  6. 6. ApplicationContext in Different Applications/java Frameworks
  7. 7. new FileSystemXmlApplicationContext
  8. 8. Servlet and Springs
  9. 9. Using new ClassPathXmlApplicationContext
  10. 10. Using new XmlWebApplicationContext
  11. 11. Using WebApplicationContextUtils.getWebApplicationContext(ServletContext)</li></li></ul><li>The confused word: IOC<br />IOC is a design pattern that externalizes application logic so that it can be injected into client code rather than written into it. Use of IOC in Spring framework separates the implementation logic from the client<br />In very simple sentence we can say, the basic concept of IOC (Inversion of Control) pattern is that you don't create your objects but describes how they should be created.<br />Let us see one problem found while programming in Java. Then we will see how IOC provides the solution of this problem.<br />
  12. 12. Problem: <br />There is a well known car racing computer game –NeedForSpeed. I have taken this example because most of us had played this game. You can Google if you want to know about this game ;)…<br />In this game, there are the participants use varieties of cars, such as<br />Ferrari<br />Jaguar<br />McLaren<br />Ford<br />Each type of car do have their own specifications say grip, accelerator, speed etc. <br />Now let’s write a program for this game. <br />There will be 1 generic class having common behavior. All the above different cars must inherit the common behavior of this generic class.<br />We will name the generic class as:- NeedForSpeedCar which should be an interface. Other car classes such as Ferrari, Jaguar, McLaren, Fordetc. must implement that interface.<br />
  13. 13. The generic class which contains the declaration of the common behavior of all the cars. This is NeedForSpeedCar.java<br />//NeedForSpeedCar.java<br />package spring.test.santosh.game;<br /> <br />public interface NeedForSpeedCar{<br />String startEngine(); <br />String accelerate();<br />}<br />Now we do have variety of cars. The specification of Ferrari is different from Jaguar and McLaren. Similarly McLaren specification is different from other cars. So each variety of car do have it's own implementaton. So let's see the implementation of those cars.<br /> <br />
  14. 14. //Ferrari.java<br />package spring.test.santosh.game;<br /> <br />public class Ferrari implements NeedForSpeedCar{<br /> public String startEngine(){<br />return ("Start engine of your Ferrari Car");<br /> }<br /> public String accelerate(){<br />return ("Accelerate and run fast your Ferrari Car");<br />} <br />} <br />//Jaguar.java<br />package spring.test.santosh.game;<br /> <br />public class Jaguar implements NeedForSpeedCar{<br /> public String startEngine(){<br />return ("Start engine of your Jaguar Car");<br /> }<br /> public String accelerate(){<br />return ("Accelerate and run fast your Jaguar Car");<br />} <br />}<br />
  15. 15. //McLaren.java<br />package spring.test.santosh.game;<br /> <br />public class McLaren implements NeedForSpeedCar{<br /> public String startEngine(){<br />return ("Start engine of your McLaren Car");<br /> }<br /> public String accelerate(){<br />return ("Accelerate and run fast your McLaren Car");<br />} <br />} <br />//Ford.java<br />package spring.test.santosh.game;<br /> <br />public class Ford implements NeedForSpeedCar{<br /> public String startEngine(){<br />return ("Start engine of your Ford Car");<br /> }<br /> public String accelerate(){<br />return ("Accelerate and run fast your Ford Car");<br />} <br />}<br />
  16. 16. The Race is going to be started. So let’s write that class…<br />//Race.java<br />package spring.test.santosh.game;<br /> <br />public class Race{ <br /> public void startRace(){<br />//You choose your car-Ferrari<br />NeedForSpeedCarmyracingcar= new Ferrari();<br />System.out.println(myracingcar.startEngine());<br />System.out.println(myracingcar.accelerate());<br /> }<br />}<br />class Race has a dependency to class Ferrari<br />The class Race has a dependency to class Ferrari.<br />Now the car modules are ready.<br />The race is ready.<br />Let’s ask the Participant to start the race. <br />The participant is ready to use Ferrari.<br />
  17. 17. // Participant.java<br />package spring.test.santosh.game;<br />public class Participant{ <br />public static void main(){<br />//You choose your car-Ferrari<br />Racerace = new Race();<br />race.startRace();<br /> }<br />}<br />Compile all the programs. And run Participant. The output would be:<br />Now it looks pretty good. The Participant run the car Ferrari.<br />See the next slide for what is the problem here…………………………………………<br />
  18. 18. The participant wants to use the another car: McLaren<br />McLaren is best for grip so he chosed this car for the race.<br />But hey… Ohhhhnooooooooooo.... <br />It's not really pretty good because of the<br />Problem here is:the object of new Ferrari is hard coded. So to use McLaren, it should be:<br />NeedForSpeedCarmyracingcar = new Ferrari();<br />NeedForSpeedCarmyracingcar = new McLaren();<br />So at any instance the participant wants to choose another car, it needs the code change in Race.java. <br />If the participant wants to change to Fordfrom McLaren, then it must be:<br />NeedForSpeedCarmyracingcar = new McLaren();<br />NeedForSpeedCarmyracingcar = new Ford();<br />
  19. 19. Solution: <br />So, what do you think, what could be the solution???? Can you change the program as per the participant’s requirement? Think a while before going down for the solution…<br />How is it if the object of your racing cars provide from outside but not in the class itself? <br />That is NeedForSpeedCarmyracingcar= <get from outside><br />This will be known as the dependency Injection (IOC)<br /> <br />Yes, it's a good approach. But who will create the object and who can provide the dependency injection to the class Race and how? <br />The answer is the IOC container provided in Sprint framework. <br />The dependency injection will be provided through <br /><ul><li>a constructor or
  20. 20. asetter Method</li></ul>So let’s restructure the classes. You need to follow few steps to work with Spring IOC.<br />
  21. 21. Step 1: Add property for the object you need to inject and write setter method.<br />//Race.java<br />package spring.test.santosh.game;<br /> <br />public class Race{ <br />NeedForSpeedCarmyracingcar;<br /> <br /> public void setMyracingcar(NeedForSpeedCarmyracingcar){<br />this.myracingcar= myracingcar;<br /> }<br /> public void startRace(){<br />//You don’t create the object of any car type//NeedForSpeedCarmyracingcar = new Ferrari();<br />System.out.println(myracingcar.startEngine());<br />System.out.println(myracingcar.accelerate());<br /> }<br />}<br />Newly added. Through the setter method the object will be injected into<br />Race class.<br />Now we need Spring Framework to provide the Dependent Injection into the class Race. So to use Spring, download the Spring Framework from http://www.springsource.org/download<br />After you download set the library files into the classpath.<br />
  22. 22. Step 2: Create the Spring Configuration XML file. This will contain the entries for the dependency injection. The object will be referred as a bean. We can give any name for this XML. Here we will name as: SpringConfig.xml<br /><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" <br /> "http://www.springframework.org/dtd/spring-beans.dtd"><br /><beans><br /> <bean id="race" class="spring.test.santosh.game.Race"><br /> <property name="myracingcar"><br /> <ref local="ferrari"/> <br /> </property><br /> </bean><br /> <bean id="ferrari" class="spring.test.santosh.game.Ferrari" /><br /> <bean id="ford" class="spring.test.santosh.game.Ford" /><br /> <bean id="mclaren" class="spring.test.santosh.game.McLaren" /><br /> <bean id="jaguar" class="spring.test.santosh.game.Jaguar" /><br /></beans><br />myracingcar is the property in Race.java. Through the setter method the object is injected into Race.java<br />You can change the ref as per the car chosen by the participant from the below bean id list. <br />These are the objects injected dynamically. The objects are created by IOC container and injected into Race.java<br />
  23. 23. Step 3: Write the client. It must use the config springconfig.xml.<br />packagespring.test.santosh.race.game;<br /> <br />importorg.springframework.context.ApplicationContext;<br />import org.springframework.context.support.FileSystemXmlApplicationContext;<br /> <br />publicclassParticipant{<br />publicstaticvoid main(String args[]){<br />ApplicationContextctx = newFileSystemXmlApplicationContext("springconfig.xml");<br /> Race race = (Race) ctx.getBean("race");<br />race.startRace();<br /> }<br />}<br />The instance of Ferrari <br />will be created.<br />Now run Driver and see the output…<br />
  24. 24. Now we will change the springconfig.xml to choose McLaren car instead of Ferrari. We will not touch any of the java file… And we will see the output after that…<br /><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" <br /> "http://www.springframework.org/dtd/spring-beans.dtd"><br /><beans><br /> <bean id="race" class="spring.test.santosh.game.Race"><br /> <property name="myracingcar"><br /> <ref local="mclaren"/> <br /> </property><br /> </bean><br /> <bean id="ferrari" class="spring.test.santosh.game.Ferrari" /><br /> <bean id="ford" class="spring.test.santosh.game.Ford" /><br /> <bean id="mclaren" class="spring.test.santosh.game.McLaren" /><br /> <bean id="jaguar" class="spring.test.santosh.game.Jaguar" /><br /></beans><br />Now ref is changed <br />to "mclaren" from "ferrari".<br />Output after you runDriver.class<br />
  25. 25. To download the source code project for this example, you can choose the link*:<br />NeedForSpeed.zip (Standalone Application)<br />*athttp://springs-download.blogspot.com<br />
  26. 26. Understanding <br />ApplicationContextandmethodgetBean("<BEAN NAME>")<br />I believe you now understand what is IOC and how we can use the Dependency Injection in Springs to make java classes/components independent as possible of other java classes.<br />Now let’s see more on the ApplicationContext and the method getBean("...") in <br />ApplicationContext.<br />ApplicationContextis the central interface to provide configuration for an application in springs.<br />An ApplicationContext provides:<br /><ul><li>The ability to load file resources in a generic fashion.
  27. 27. Bean factory methods for accessing application components.</li></ul>And many more…<br />Now we will see how ApplicationContext is used to load the file resources. Here we are loading the Spring Config file -springconfig.xml<br />
  28. 28. new FileSystemXmlApplicationContext<br />//Partifipant.java<br />public class Participant{<br /> public static void main(String args[]){<br />ApplicationContextctx = new FileSystemXmlApplicationContext("springconfig.xml");<br /> Race race = (Race) ctx.getBean("race");<br />race.startRace();<br />}<br />}<br />ApplicationContextctx = new FileSystemXmlApplicationContext("springconfig.xml")<br />The Application Context object:<br /><ul><li>reads the springconfig.xml.
  29. 29. collects all the bean id’s as defined in springconfig.xml. Say: race, ferrari, ford, McLaren.
  30. 30. saves the instances of each bean class into Map with key as the bean id such as:</li></li></ul><li>Now we will see the getBean() method from ApplicationContext class. <br />Race race = (Race) ctx.getBean("race")<br />It is very important to know the scopes of the Beans when you do use the method: ctx.getBean("<bean name>"). We will discussed in latter sections about these scopes. For the time being, you understand the use of getBean() method.<br />As discussed, the getBean() method returns an instance, which may be shared or independent of the specified bean. This method allows a Spring BeanFactory to be used as a replacement for the Singleton or Prototype design pattern. Callers may retain references to returned objects in the case of Singleton beans. <br />I would request you to go through back the previous slides and see the XML bean configuration and the Participant.java class to understand how it behaves. <br />
  31. 31. ApplicationContextinDifferent Applications/java Frameworks<br />Till now we learned how we configure the Spring IOC (Independent Injection) by configuring the XML configuration file.<br />So in the example you can notice the below line in Participant.java:<br />ApplicationContextctx = newFileSystemXmlApplicationContext("springconfig.xml");<br />Here we are creating the object of FileSystemXMLApplicationContext by providing the XML name as argument. Our application is a stand-alone application and so simply we could use new FileSystemXMLApplicaitonContext(<XML file path>). Also this class constructor is helpful to create the Spring application context for test harness or unit testing.<br />But there are different applications say Web application such as servlets/jsp's, Enterpriseapplications such as EJBs with Java Frameworks such as Struts, JSF etc. So in this section we will see how we can configure Springs IOC and how we will get the ApplicationContext in client.<br />
  32. 32. Servlet andSprings<br />I hope you are good in writing the Servlet and JSP application. So here I am not going to put how to build the servlet application and deploy it in the server.<br />Just recall the directory structure in your servlet project:<br />Now we will see where we can store our spring config XML file and how it could be accessible in the servlet classes.<br />Note: It is very important that you don’t be confused this example with Springs MVC. We will see the Spring MVC latter. So now you concentrate how you will get the Spring ApplicationContext object in Servlet.<br />
  33. 33. Achieving Springs Application Context in Servlet<br />You can get the ApplicationContext of Spring in Servlet in 3 ways:<br />Through new ClassPathXmlApplicationContext("<relative path of config XML>")<br />Through new XmlWebApplicationContext()<br />Through WebApplicationContextUtils.getWebApplicationContext(ServletContext);<br />
  34. 34. Using ClassPathXmlApplicationContext<br />The ClassPathXmlApplicationContextconstructor searches the given XML file from the classes folder in WEB-INF folder. Just you need to follow some basic steps.<br />step 1: Create the spring config XML file. <br />step 2: Name that file whatever you want. For example, in our example we named as: myspringconfig.xml<br />step 3: Put this xml file in WEB-INF/classes folder while youare deploying. (If you use any editor like Eclipse, just put the XML in src folder, so when you build your project, it will automatically generate the same copy of XML along with the .class files in WEB-INF/classes folder.)<br />Step 4: In servlet you can simply create the object of ClassPathXmlApplicationContextby passing the file relative path in constructor. E.g. <br />ApplicatonContextctx = <br />new ClassPathXmlApplicationContext("spring/test/santosh/config/myspringconfig.xml"); <br />Herespring.test.santosh.configis a package created and stored the myspringconfig.xmlin this package.<br />Let’s see the servlet example.<br />
  35. 35. Let’s convert the same stand-alone application into servlet application by very minimum changes. <br /><ul><li>The NeedForSpeedCar.java, Ferrari.java, Ford.java, Jaguar.java, McLaren.java will remain unchanged
  36. 36. The Spring Configfile – myspringconfig.xml will also remain unchanged. But you create a new packagespring.test.santosh.config and place this XML there.
  37. 37. In Race.java a small change. The output should be in HTML formar. So to support the ServletOutPutStream, we will just do a small change in startRace(…) method as</li></ul>public void startRace(PrintStream out) {<br />out.println("<HTML><BODY>");<br />out.println("<FONT color='red' size='5'>");<br />out.println(myracingcar.startEngine());<br />out.println("<BR>");<br />out.println(myracingcar.accelerate());<br />out.println("</FONT></BODY></HTML>");<br />}<br /><ul><li>Now in the place of Participant.java, we will write a Servlet and name the servlet as: ParticipantServlet.java. In the init method, create the object of ApplicatonContext:</li></ul>public void init(ServletConfigconfig) throws ServletException {<br />super.init(config);<br />ctx = new ClassPathXmlApplicationContext("spring/test/santosh/config/myspringconfig.xml");<br />System.out.println("XML found in classpath...");<br />}<br />
  38. 38. In the service (doPost) method, get the Bean<br />public void doPost(HttpServletRequest request, HttpServletResponse response)<br />throws ServletException, IOException {<br />Race race = (Race) ctx.getBean("race");<br />PrintStream out = new PrintStream(response.getOutputStream());<br />race.startRace(out);<br />}<br />Output<br />To download the source code for this project for this example, you can choose the link*:<br />NeedForSpeedServletOne.zip (Using ClassPathXmlApplicationContext)<br />*athttp://springs-download.blogspot.com <br />
  39. 39. UsingXmlWebApplicationContext<br />The XmlWebApplicationContextconstructor searches the applicationContext.xmlfile fromthe WEB-INF folder where the web.xml is located. See the constructor, you don’t pass the XML file name. So to get the context you simply use as:<br />XmlWebApplicationContextctx = new XmlWebApplicationContext();<br />ServletContextservletContext = servletConfig.getServletContext();<br />ctx.setServletContext(servletContext);<br />ctx.refresh();<br />Race race = (Race) ctx.getBean("race");<br />XML File searches the applicationContext.xml from WEB-INF folder and then loads the bean classes.<br />To download the source code for this project for this example, you can choose the link*:<br />NeedForSpeedServletTwo.zip (Using XmlWebApplicationContext)<br />*athttp://springs-download.blogspot.com <br />
  40. 40. UsingWebApplicationContextUtils.getWebApplicationContext(ServletContext)<br />When you use WebApplicationContextUtils.getWebApplicationContext(servletContext), you need to add ContextLoaderListener in web.xml as:<br /><listener><br /> <listener-class><br />org.springframework.web.context.ContextLoaderListener<br /> </listener-class><br /></listener><br />And when you use<br />ServletContextservletContext = config.getServletContext();<br />ctx= WebApplicationContextUtils.getWebApplicationContext(servletContext); <br />Race race = (Race) ctx.getBean("race");<br />XML File searches the applicationContext.xml from WEB-INF folder and then loads the bean classes.<br />
  41. 41. So now you understood that, you can use <br />ApplicationContextctx= WebApplicationContextUtils.getWebApplicationContext(ServletContextservletCtx);<br />For that you need to add the ContextLoaderListenerclass in web.xml under the tag <listener><br />To download the source code for this project for this example, you can choose the link*:<br />NeedForSpeedServletThree.zip (Using WebApplicationContextUtils)<br />*athttp://springs-download.blogspot.com <br />
  42. 42. Have you ever asked the question<br /><ul><li>Is it possible to use the spring configXML as you name and that too more than one such configxmls? </li></ul>Scenario<br />I want to separate the bean entries in two spring configxmls as:<br />springconfig.xml<br />racingcar.xml<br />springconfig.xml will contain the bean definition for spring.test.santosh.game.Race.<br />racingcar.xml will contain the bean definition for spring.test.santosh.game.Ferrari, spring.test.santosh.game.Ford, spring.test.santosh.game.McLaren and spring.test.santosh.game.Jaguar<br />They both will look like:<br />springconfig.xml<br /><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"><br /><beans><br /> <bean id="race" class="spring.test.santosh.game.Race"><br /> <property name="myracingcar" ref="ford" /><br /> </bean><br /></beans><br />
  43. 43. racingcar.xml<br /><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"><br /><beans><br /> <bean id="ferrari" class="spring.test.santosh.game.Ferrari" /><br /> <bean id="ford" class="spring.test.santosh.game.Ford" /><br /> <bean id="mclaren" class="spring.test.santosh.game.McLaren" /><br /> <bean id="jaguar" class="spring.test.santosh.game.Jaguar" /><br /></beans><br />And the answer will be, Yes… It is possible…<br />To use multiple custom defined XMLs, you need 2 entries in web.xml. <br /><ul><li>One is as already discussed – adding the ContextLoaderListenerclass under the TAG <listener>
  44. 44. And the second is, adding the parameters in <context-param> TAG with param-name as contextConfigLocation.xml.</li></ul><listener><br /> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class><br /></listener><br /><context-param><br /> <param-name>contextConfigLocation</param-name><br /> <param-value><br /> /WEB-INF/springconfig.xml,<br /> /WEB-INF/racingcar.xml<br /> </param-value><br /></context-param><br />
  45. 45. Here you need not worry on updating/changing the XML file names in the java file such as ParticipantServlet.java. When you add any extra more spring config xml, just you need to update in web.xml under the tag <param-value> as shown in the previous slide.<br />To download the source code for this project for this example, you can choose the link*:<br />NeedForSpeedServletFour.zip (Using multiple spring config XMLs)<br />*athttp://springs-download.blogspot.com <br />
  46. 46. End of Part-1<br />In part – 1 we learned the basics of Spring.<br />In further parts we will see,<br /><ul><li>Part – 2 : Spring - working with Databases</li></ul> at http://javacompanionbysantosh.blogspot.com/2011/10/spring-and-database.html<br /><ul><li>Part – 3 :Spring and Hibernate</li></ul>at http://javacompanionbysantosh.blogspot.com/2011/10/spring-and-hibernate.html<br /><ul><li>Part – 4 : Spring - Managing Database Transactions</li></ul> at http://javacompanionbysantosh.blogspot.com/2011/10/managing-transactions-in-spring.html<br /><ul><li>Part – 5 : Spring - Security</li></ul> at http://javacompanionbysantosh.blogspot.com/2011/10/spring-security.html<br /><ul><li>Part – 6: Spring AOP</li></ul>athttp://javacompanionbysantosh.blogspot.com/2011/10/spring-aop.html<br /><ul><li>Part – 7 : Spring MVC</li></ul> athttp://javacompanionbysantosh.blogspot.com/2011/10/spring-mvc.html<br />
  47. 47. Do you have Questions ?<br />Please write to:santosh.bsil@yahoo.co.in<br />
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.