Write a ‘Hello Spring!’ program in 10 minutes with eclipse


Released in the spring of 2003, Spring framework has been doing lot of heavy lifting of developing enterprise Java applications up to now. Compared with J2EE, Spring is very lightweight framework and consist of more elaborate features like Inversion of Control(IOC) container, Aspect Oriented Programming (AOP), Web MVC framework and so on.

In this tutorial, we are going to create an extremely simple traditional ‘hello world’ application using Spring framework and eclipse IDE. This would be very useful for Spring newbies.

Step 1: Download and install the Spring framework

Before we move further download the Spring framework from http://www.springsource.org/download. Spring comes in two flavors, with all dependencies and without dependencies. For beginners, I highly recommend you to choose the ‘with dependencies’ flavor because we don’t want to hunt for the dependencies later and it might take a whole day perhaps.

After downloading, extract it to a folder of your choice (for example, C:\ on Windows or /opt/ on UNIX)

 

If you examine the folder structure of Spring distribution, you would see following important folders

  • dist – Contains spring framework.jar
  • docs – Contains documents.
  • lib – Contains all dependent libraries.
  • src – Contains source code.

 

But don’t get confused with all these .jar files. To create our application, we only need the spring.jar file which resides in the dist folder and commons-logging.jar file in lib/jakarta-commons folder.

Now we have downloaded the Spring framework libraries. So lets setup a project using eclipse.

Step 2 : Setting up your project using eclipse

eclipse is a great IDE for enterprise Java application development. But you don’t have to limit only to eclipse, there are several IDEs out there such as NetBeans, IntelliJ IDEA and even Spring IDE ( a plugin for eclipse that make easier the Spring application development). So the selection is completely up to you. Here I choose d eclipse because I’m a fan of eclipse for a long time.

I’ll use the latest eclipse release eclipse Galileo for Java EE development. You can download it by visiting http://www.eclipse.org/downloads/

So lets begin coding our application

 

Fire up eclipse and go to File > New Java Project. This will bring you the new project creation dialog. Enter HelloSpring as the project name and be sure to set Project Layout as Create separate folders for sources and class files. Leave other options as it is and click on Next.

New Project Creation Dialog
New Project Creation Dialog

 

Then eclipse will show you another dialog and ask you to configure your Java Build Path. Click on the Libraries tab and select Add External Jars. This is place where we can add Spring framework libraries to our project. So browse for the Spring extraction folder and select dist/spring.jar and lib/jakarta-commons/commons-logging.jar.

This would like the following.

Set Java Build Path
Set Java Build Path

 

Then click on Finish.

 

Step 3: Create a simple Spring bean.

Now we’ve setup the project and configured it to get Spring support. All we have to do is start coding the application.

As the first step, I’m gonna create a simple Java class called “HelloSpring”.

public class HelloSpring {

 private String message;

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

 public String getMessage() {
 return message;
 }

 public void sayHello() {
 System.out.println(message);
 }

}

This is a kind of Spring bean which is very similar to simple POJO class. It has a property called ‘message’ and we are going to print a message to the screen using this class. Create the above class using eclipse and place it under com.dunithd.hellospring package.

 

Step 4: Create beans.xml file

We need to tell Spring about our HelloSpring bean. For this purpose, Spring uses a bean descriptor file which is a XML file and holds information about all Spring beans in your application.

 

Create the following XML file in your classpath and name it as beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

 <bean id="helloSpring" class="com.dunithd.hellospring.HelloSpring">
 <property name="message" value="Hello Spring!" />
 </bean>

</beans>

Step 5 : Create the main program

I’m gonna create a simple Java program which prints ‘Hello Spring!” to the screen. So I should have main method which invokes the HelloSpring bean.

Create the following class and place it under the same package.

package com.dunithd.hellospring;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {

        //load the beans.xml file from the project's classpath
        ApplicationContext context =
            new ClassPathXmlApplicationContext(
                    "beans.xml");
        BeanFactory factory = (BeanFactory) context;    //build the factory

        //obtain the bean from factory
        HelloSpring helloSpring = (HelloSpring) factory.getBean("helloSpring");

        //Most of the heavy lifting is done by Spring, now use the helloSpring object as your wish
        helloSpring.sayHello();

    }

}

By looking at the main program we can observe that Main class does not directly instantiate the HelloSpring bean, instead it delegates the Creation Responsibility to the Spring container. So in this

 

case, Spring acts as a kind of Factory object. This is the most important aspect of Spring, which is Ability to Create Objects and this approach leads us to create loosely coupled software components.

Step 6 : Add logging configuration file to the project

The Spring framework uses Apache Commons Logging (about which information is available at http://jakarta.apache.org/ commons/logging/) to log container and application information . We’ve add the commons-logging.jar file to our project  because of this reason.

So create a file called log4j.properties and place it under root of the classpath with following content.

log4j.rootLogger=FATAL, first
log4j.appender.first=org.apache.log4j.ConsoleAppender
log4j.appender.first.layout=org.apache.log4j.PatternLayout
log4j.appender.first.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

 

Now we have reached to the end of our application development. If you followed the above steps correctly, your eclipse project would looks like follows.

Package exploerer view in eclipse
Package exploerer view in eclipse

Now right click on the Main.java file and select Run As > Java Application from the context menu.

Then you’ll see an output like this.

 

Output of the HelloSpring application
Output of the HelloSpring application

You can change the output message by changing the message property in beans.xml.

What we have done so far?

Using beans.xml, we’ve told Spring that what types of beans should be instantiated and what properties should be injected to that beans. As you saw, Spring container reads the message property from beans.xml and injected it into the HelloSpring bean.

Beside these things, Main program is not aware of creating beans and injecting dependencies. So the whole application is well decoupled.

Thats the power of Spring!

This is very simple application of Spring and this doesn’t reflects the full Inversion of Control capability of that. But if you are a Spring newbie, this would be a good starting point.

Download the source code for the HelloSpring application here

 

Now right click on the Main.java file and select Run As > Java Application from the context menu.Then you’ll see an output like this.You can change the output message by changing the message property in beans.xml.What we have done so far?

Using beans.xml, we’ve told Spring that what types of beans should be instantiated and what properties should be injected to that beans. As you saw, Spring container reads the message property from beans.xml and injected it into the HelloSpring bean.

Beside these things, Main program is not aware of creating beans and injecting dependencies. So the whole application is well decoupled.

Thats the power of Spring!

This is very simple application of Spring and this doesn’t reflects the full Inversion of Control capability of that. But if you are a Spring newbie, this would be a good starting point.