Spring Hello World

Be sure you followed the complete list of tasks for Eclipse with Spring STS before attempting these instructions.

If you did not, do this first -> Spring-IDE-Download

Select the spring perspective:

Select a new Spring Project

Name it "HelloWorld"

Also set the Source folder to: src\main\java

Add a package to your project: com.qbytesworld

Create a new POJO Class called HelloWorld and place the following code in it:

package com.qbytesworld;
public class HelloWorld {
private String message;
public void setMessage(String message) {
this.message = message;
}
public void display() {
System.out.println(message);
}
}

The HelloWorld class has a message property and its value is set using the setMessage() method. This is called setter injection. Instead of directly hard coding the message, we inject it through an external configuration file. The design pattern used here is called Dependency Injection design pattern. The HelloWorld class also has a display() method to display the message.

Now we have created the HelloWorld bean class, the next step is to add an entry for this in the bean configuration file. The bean configuration file is used to configure the beans in the Spring IoC container. To create a new bean configuration file right click the src folder and select New -> Spring Bean Configuration File.

Here is the key to getting it to work.

Be sure the "Spring project nature" is clicked, without it, you will spend hours of digging into messages that make no sence.

At the moment I do not know what the options are, so we are taking the default, click finish.

Within the <beans> tag, place this code:

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

What this is telling us is:

  • Create a bean called helloWorld using our nameSpace com.qbytesworld
  • Set the property message to the value of Hello World!

Now we can implement the code by creating a class that contains the main(String[] args) call HelloWorldApp

package com.qbytesworld;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.FileSystemResource;
public class HelloWorldApp {
public static void main(String[] args) {
BeanFactory factory = new XmlBeanFactory(new FileSystemResource(
"beans.xml"));
HelloWorld helloWorld = (HelloWorld) factory.getBean("helloWorld");
helloWorld.display();
}
}

The above code will have compile error until we update our Build Path.

We need to add the following External JAR files:

These two do not come from spring:

If you did not follow the Spring STS instructions at the beginning, you will have problems here.

Try running the Spring project as a Java Application.