Hello Word Example in Spring

13
Hello Word Example in Spring : Chapter 3 Posted by Dinesh Rajput In this tutorial you will write first application in your spring framework with STS tool. In previous you set up the Spring Environment of your Local machine. So let us proceed to write a simple Spring Application which will print "Hello World!" message based on the configuration done in Spring Beans Configuration file. Step 1 - Create Spring Project: The first step is to create a simple Spring Project using STS IDE. Follow the option File -> New -> Project and finally select Spring Project wizard from the wizard list. Now name your project as spring01HelloWorld using the wizard window as follows:

description

Hello world Spring

Transcript of Hello Word Example in Spring

Hello Word Example in Spring : Chapter 3 Posted by Dinesh Rajput In this tutorial you will write first application in your spring framework with STS tool. In previous you set up the Spring Environment of your Local machine.So let us proceed to write a simple Spring Application which will print "Hello World!" message based on the configuration done in Spring Beans Configuration file.

Step 1 - Create Spring Project:The first step is to create a simple Spring Project using STS IDE. Follow the option File -> New -> Project and finally select Spring Project wizard from the wizard list. Now name your project as spring01HelloWorld using the wizard window as follows:

Once your project is created successfully, you will have following content in your Project Explorer:

Step 2 - Add Required Libraries:As a second step let us add Spring Framework and common logging API libraries in our project. To do this, right click on your project name spring01HelloWorld and then follow the following option available in context menu: Build Path -> Add Libraries... display window as follows:

In next window wizard click on User Library >> Next as following:

After Next add user library name as spring-lib and add following minimum required jar files to this user library : antlr-runtime-3.0.2 org.springframework.aop-3.2.0.M1 org.springframework.asm-3.2.0.M1 org.springframework.aspects-3.2.0.M1 org.springframework.beans-3.2.0.M1 org.springframework.context.support-3.2.0.M1 org.springframework.context-3.2.0.M1 org.springframework.core-3.2.0.M1 org.springframework.expression-3.2.0.M1 commons-logging-1.1.1

Step 3 - Create Source Files:Now let us create actual source files under the spring01HelloWorld project. First we need to create a package called com.sdnext.dineshonjava.tutorial. To do this, right click on src in package explorer section and follow the option : New -> Package.

Next we will create HelloWorld.java and SpringTestApp.java files under the com.sdnext.dineshonjava.tutorial package.

HelloWorld.javaview plainprint?1. packagecom.sdnext.dineshonjava.tutorial;2. 3. publicclassHelloWorld{4. privateStringmessage;5. 6. publicvoidsetMessage(Stringmessage){7. this.message=message;8. }9. 10. publicvoidgetMessage(){11. System.out.println("YourMessage:"+message);12. }13. }SpringTestApp.javaview plainprint?1. packagecom.sdnext.dineshonjava.tutorial;2. 3. importorg.springframework.context.ApplicationContext;4. importorg.springframework.context.support.ClassPathXmlApplicationContext;5. 6. publicclassSpringTestApp7. {8. publicstaticvoidmain(String[]args)9. {10. //ClassPathXmlApplicationContextisloadallbeansintheapplication11. ApplicationContextcontext=newClassPathXmlApplicationContext("spring.xml");12. 13. //thisstepisusedtogetrequiredbeanusinggetBean()methodofthecreatedcontext14. HelloWorldhelloWorld=(HelloWorld)context.getBean("helloWorld");15. helloWorld.getMessage();16. }17. }

There are following two important points to note about the main program:1. First step is to create application context where we used framework API ClassPathXmlApplicationContext(). This API loads beans configuration file and eventually based on the provided API, it takes care of creating and initializing all the objects ie. beans mentioned in the configuration file.2. Second step is used to get required bean using getBean() method of the created context. This method uses bean ID to return a generic object which finally can be casted to actual object. Once you have object, you can use this object to call any class method.Step 4 - Create Bean Configuration File:Now we have to create Bean Configuration file which is an XML file which maintain all classes object as bean. It is also called as Bean Factory Configuration. Keep this file(spring.xml) on the src directory of the spring project.The spring.xml is used to assign unique IDs to different beans and to control the creation of objects with different values without impacting any of the Spring source files. For example, using below file you can pass any value for "message" variable and so you can print different values of message without impacting HelloWorld.java and SpringTestApp.java files. Let us see how it works:spring.xmlview plainprint?1. 3. 4. 5. 6. 7. After creation of the bean configuration file(Spring.xml), now we put this file into "src" directory of the application(i.e. which is present in classpath). Then configuration file(Spring.xml) is loaded in the ApplicationContext as follows.view plainprint?1. ApplicationContextcontext=newClassPathXmlApplicationContext("spring.xml");

Now suppose we put configuration file(Spring.xml) into the different directory package other than "src" like "com.dineshonjava.sdnext.springConfig" then we have to give classpath of configuration file(Spring.xml) to ApplicationContext as follows:view plainprint?1. ApplicationContextcontext=newClassPathXmlApplicationContext("classpath:com/dineshonjava/sdnext/springConfig/spring.xml");

We can use wildcard for this as follows:view plainprint?1. ApplicationContextcontext=newClassPathXmlApplicationContext("classpath*:com/dineshonjava/**/springConfig/spring.xml");

view plainprint?1. ApplicationContextcontext=newClassPathXmlApplicationContext("classpath*:com/*/**/springConfig/*-spring.xml");

When Spring application gets loaded into the memory, Framework makes use of the above configuration file to create all the beans defined and assign them a unique ID as defined in tag. You can use tag to pass the values of different variables used at the time of object creation.

Now run the program you will get following output on console.

Output:Jun 16, 2012 4:45:17 PM org.springframework.context.support.AbstractApplicationContext prepareRefreshINFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@145d068: startup date [Sat Jun 16 16:45:17 IST 2012]; root of context hierarchyJun 16, 2012 4:45:17 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitionsINFO: Loading XML bean definitions from class path resource [spring.xml]Jun 16, 2012 4:45:18 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletonsINFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@15212bc: defining beans [helloWorld]; root of factory hierarchyYour Message : Hello World!

In the Next chapter we will discuss about the IoC Contianer in its role in the Spring Framework.