Spring 3 Hello World Example

In this example we will learn how to create a simple hello world example in Spring 3.0. 

Folder Structure:

  1. Create a new Java Project  SpringCoreTutorial” and create a package for our src files com.javainterviewpoint
  2. Add the required libraries to the build path. Java Build Path ->Libraries ->Add External JARs and add the below jars.

    commons-logging-1.1.1.jar
    spring-beans-3.2.9.RELEASE.jar
    spring-core-3.2.9.RELEASE.jar

  3. Create the Java classes HelloWorldBean.java and Logic.java under  com.javainterviewpoint folder.
  4. Place the SpringConfig.xml under the src directory

HelloWorldBean.java

  • Our HelloWorldBean class contains property message, for which we will set the value through our Logic class.
  • The show() method prints the value which has been set by the Logic class
package com.javainterviewpoint;

public class HelloWorldBean 
{
    private String message;

    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public void show()
    {
        System.out.println("Welcome to "+message+" - JavaInterviewPoint");
    }
}

Logic.java

  • In our Logic class, We use Resource to read the configurationfile(SpringConfig.xml).
  • We will get our “HelloWorldBean” instance through the BeanFactory which reads up all the bean available in the Configuration File.
  • We set the value to message property of the HelloWorldBean and we will call our show() method.
package com.javainterviewpoint;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;


public class Logic 
{
    public static void main(String args[])
    {
        //Create a Resource to read the configuration file
        Resource resource = new ClassPathResource("SpringConfig.xml");
        //Read the beanfactory of the configuration file
        BeanFactory bf = new XmlBeanFactory(resource);
        //Get the HelloWorldBean object
        HelloWorldBean helloWorldBean = (HelloWorldBean)bf.getBean("helloWorldBean");
        //Set value to the message property in the helloWorldBean class
        helloWorldBean.setMessage("Hello World");
        //Lets now call the show() method
        helloWorldBean.show();
    }
}

SpringConfig.xml

All the beans which is available will be declared in the SpringConfig file

 <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>
 <bean id="helloWorldBean" class="com.javainterviewpoint.HelloWorldBean"></bean>
</beans>

Output

Once we run our Logic cass we will get the below output

Welcome to Hello World - JavaInterviewPoint

Leave a Reply

Your email address will not be published. Required fields are marked *