Monday, July 05, 2010

Simple Spring Example














Simple Spring Example:
This is a simple Spring Program that display the helloWorld string using Spring IOC(Inversion of Control) and DI(Dependency Injection concept). In addition to the helloworld display an add() Function is added to display and perform simple addition of the two value.

Step to Create Simple Spring Example

Tool used:

1) STS Spring Source Tool

Steps:

1) Right Click on the Explorer Play ground and create a Web Dynamic Project.
2) Add all necessary jar to lib folder (Coming as Package for Spring Frame Work.)

Spring3HelloWorld:

package springExample;

public class Spring3HelloWorld {

public void sayHello(){

System.out.println("Hello Spring 3.0");

}

public int add(int a, int b)

{

return a+b;

}

}

Spring3HelloWorldTest:

package springExample;

//Please refer to http://www.roseindia.net/spring/index.shtml for more details

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.ClassPathResource;

public class Spring3HelloWorldTest {

public static void main(String[] args) {

XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("SpringHelloWorld.xml"));

Spring3HelloWorld myBean = (Spring3HelloWorld) beanFactory.getBean("Spring3HelloWorldBean");

myBean.sayHello();

int c = myBean.add(2, 3);

System.out.println("c::::::::::::::"+c);

}

}

SpringHelloWorld.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" 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="Spring3HelloWorldBean" class="springExample.Spring3HelloWorld" />

beans>

No comments: