Spring Hello World Example

In this article you will learn, how to write a Simple Spring Application using Maven 2 which print “Hello World” message. Howerver this message can be configured through Spring Beans Configuration file.

1. Create Project

Create a New Maven Project as shown in Figure 2.1

Figure 2.1 Figure 2.1

2. Create Bean Configuration File

Now create Bean Configuration File as showin Figure 2.2 and name it Spring-Bean.xml

Figure 2.2 Figure 2.2


Add the following code in Spring-Bean.xml

<bean id="helloWorld" class="com.kruders.HelloWorld">
   <property name="message" value="Hello World!"/>
</bean>

3. Add Spring dependency

Write the following code in pom.xml to add Spring 3 dependency

<properties>
   <spring.version>3.0.6.RELEASE </spring.version>
</properties>
<dependencies>
 
   <!-- Spring 3 dependencies -->
   <dependency>
       <groupId>org.springframework </groupId>
       <artifactId>spring-core </artifactId>
       <version>${spring.version} </version>
   </dependency>
 
   <dependency>
       <groupId>org.springframework </groupId>
       <artifactId>spring-context </artifactId>
       <version>${spring.version} </version>
   </dependency>
 
</dependencies>

4. Create Source File

Now create a Java File HelloWorld.java in com.kruders package.

package com.kruders;
 
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class HelloWorld {
    private String name;
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
      
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Bean.xml");
  
        HelloWorld helloWorld = (HelloWorld) context.getBean("helloBean");
        System.out.println("Message : " + helloWorld.getName());
    }
}

The folder structure of the example is shown below in Figure 2.3

Figure 2.3 Figure 2.3

You can download the source code of this example here.

No comments yet.

Leave a Reply