Tuesday, January 12, 2010

Simple Spring 3 tutorial

Here goes a tutorial to get your feet wet with a (really) simple Java Application using the latest version of Spring.

1- Create a simple Java project named "SimpleSpring3"

 2- Create a "lib" in your project right under your "src" folder, then download the latest Spring version and copy the jars to "lib". Also copy "commons-logging.jar" located in the following location "projects/spring-build/lib/ivy" in the unzipped Spring file. Your library should look like this

3- Create a "SimpleSpring3" java class in the "com.greensoft" package, this class will contain one simple "sayHola" method that prints "Hola Spring 3.0!!" in the console

4- Create the Spring config "SimpleSpring3.xml" file located in the "src" folder

5- Add the following code to the Spring config file

 <beans xmlns="http://www.springframework.org/schema/beans"  
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"  
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
      <bean id="SimpleSpring3Bean" class="com.greensoft.SimpleSpring3" />  

The code in the config file defines a bean that can be accessed later on from our test file using the bean factory

6- Create the test file "SimpleSpring3Test" and the following code

 package com.greensoft;  
 import org.springframework.beans.factory.xml.XmlBeanFactory;  
 import org.springframework.core.io.ClassPathResource;  
 public class SimpleSpring3Test {  
      public static void main(String[] args) {  
           XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(  
           SimpleSpring3 simpleSpringBean = (SimpleSpring3) beanFactory  

In the above code we use XmlBeanFactory to get access to our config file "SimpleSpring3.xml" in order to get our "SimpleSpring3Bean" object.

7- The final project structure should look like this

8- Execute the code by right clicking on the test file "SimpleSpring3Test" then --> Run As --> Java Application" and you should get the following output in the console

simple, right? I hope it was useful for someone out there, that's it for now ;)