Spring Hello World Example

In this tutorial you will write first spring hello world example using 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:

 

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

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:

 

step1spring

 

In next window wizard click on User Library >> Next as following:
step1spring
 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
Spring Hello World Example

 

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.
Hello World Example

 

HelloWorld.java

package com.sdnext.dineshonjava.tutorial;

public class HelloWorld {
 private String message;

    public void setMessage(String message){
       this.message = message;
    }

    public void getMessage(){
       System.out.println("Your Message : " + message);
    }
}

SpringTestApp.java

package com.sdnext.dineshonjava.tutorial;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTestApp 
{
 public static void main(String[] args) 
 {
       //ClassPathXmlApplicationContext is load all beans in the application
              ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
       
              //this step is used to get required bean using getBean() method of the created context
       HelloWorld helloWorld= (HelloWorld) context.getBean("helloWorld");
       helloWorld.getMessage();
    }
}

 

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.xml

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemalocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    
  <bean class="com.sdnext.dineshonjava.tutorial.HelloWorld" id="helloWorld">
       <property name="message" value="Hello World!">
  </property></bean>
</beans>

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.

ApplicationContext context = new ClassPathXmlApplicationContext("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:

ApplicationContext context = new ClassPathXmlApplicationContext("classpath:com/dineshonjava/sdnext/springConfig/spring.xml");

We can use wildcard for this as follows:

ApplicationContext context = new ClassPathXmlApplicationContext("classpath*:com/dineshonjava/**/springConfig/spring.xml");

 

ApplicationContext context = new ClassPathXmlApplicationContext("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 prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@145d068: startup date [Sat Jun 16 16:45:17 IST 2012]; root of context hierarchy
Jun 16, 2012 4:45:17 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring.xml]
Jun 16, 2012 4:45:18 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@15212bc: defining beans [helloWorld]; root of factory hierarchy
Your Message : Hello World!
Spring Hello World
Spring Related Topics you may like

  1. Spring Interview Questions and Answers
  2. Spring AOP Interview Questions and Answers
  3. Spring MVC Interview Questions
  4. Spring Security Interview Questions and Answers
  5. Spring REST Interview Questions and Answers
  6. Spring Boot Interview Questions and Answers
  7. Spring Boot Microservices Interview Questions and Answers
  8. Dependency Injection (DI) in Spring
  9. Spring IoC Container
  10. What is Bean Factory in Spring
  11. ApplicationContext in Spring
  12. Bean Autowiring in Spring
  13. Spring Bean Scopes
  14. Create Custom Bean Scope in Spring Example
  15. Using ApplicationContextAware in Spring
  16. Spring Bean Life Cycle and Callbacks
  17. BeanPostProcessor in Spring
  18. BeanFactoryPostProcessor in Spring
  19. Annotations in Spring and Based Configuration
  20. Spring JSR-250 Annotations
  21. JSR 330 Annotations in Spring
  22. Spring @Component, @Repository, @Service and @Controller Stereotype Annotations
  23. Method injection with Spring using Lookup method property
  24. Spring AOP-Introduction to Aspect Oriented Programming
  25. @Aspect Annotation in Spring
  26. Spring AOP AspectJ @Before Annotation Advice Example
  27. Spring AOP Before Advice Example using XML Config
  28. Spring AOP AspectJ @After Annotation Advice Example
  29. Spring AOP After Advice Example using XML Config
  30. Spring AOP AspectJ @AfterReturning Annotation Advice Example
  31. Spring AOP After-Returning Advice Example using XML Config
  32. Spring AOP AspectJ @AfterThrowing Annotation Advice Example
  33. Spring AOP After Throwing Advice Example using XML Config
  34. Spring AOP AspectJ @Around Annotation Advice Example
  35. Spring AOP Around Advice Example using XML Config
  36. Spring AOP Proxies in Spring
  37. Spring AOP Transaction Management in Hibernate
  38. Spring Transaction Management
  39. Spring Declarative Transaction Management Example
  40. Spring AOP-Ordering of Aspects with Example
  41. Spring Security Java Based Configuration with Example
  42. Spring Security XML Namespace Configuration Example
In the Next chapter we will discuss about the IoC Contianer in its role in the Spring Framework.

                                                  << Previous || Next >>




Previous
Next

6 Comments

  1. Anonymous June 16, 2012
  2. SweeT RascalS February 6, 2013
  3. Anamika February 6, 2013
  4. suresh June 23, 2018
  5. Dinesh Rajput June 24, 2018
  6. KAMARAJ JAWAHAR August 7, 2019