This
is one of the simplest program, which uses DI (Dependency Injection)
feature of Spring.
For
this tutorial you need Spring_2.5.jar
and commons-logging-1.1.1.jar
file.
I
am using NetBeans 7.2 for this tutorial..
Lets
Start -
1.
Create a class with main function, in my example i am creating class
FirstSpringProgram.java containing main class.
FirstSpringProgram.java
/**
*
* @author Vikas Kumar Verma
*/
public class FirstSpringProgram {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
System.out.println("JSR");
/**
* Create and dispense bean, It load Bean Definition and wire bean
* together.
*/
ApplicationContext applicationContext
= new FileSystemXmlApplicationContext(
"E:\\vikas\\rnd\\FirstSpringProgram\\Spring.xml");
/**
* Get Bean using Bean ID declred in Spring.xml file.
*/
SpringBean springBean = (SpringBean) applicationContext.getBean("SpringBean");
/**
* Executing the bean method.
*/
System.out.println("Out put from Spring Bean: " + springBean.callSpring());
System.out.println("Thanks");
}
} /* End of class */
2.
Now we need to create Interface which represent the Spring Bean, Name
this file as
SpringBean.java -
/*
* Interface declaring prototype of Spring Bean
*/
package firstspringprogram.bean;
/**
*
* @author Vikas Kumar Verma
*/
public interface SpringBean {
/**
* Bean Method return bean message.
*
* @return String
*/
public String callSpring();
}
/* End of class */
3.
Create a Bean class implimenting SpringBean Interface, as
SpringBeanImpl.java
SpringBeanImpl.java -
package firstspringprogram.bean;
/**
* @author : Vikas Kumar Verma
*/
public class SpringBeanImpl implements SpringBean {
/**
* Bean Method return bean message.
*
* @return String
*/
@Override
public String callSpring() {
/**
* Return Bean Message
*/
return "Thank You for Calling Me ... ";
}
}
/* End of class */
4.
Now we have to map the bean with spring container, to do this
you
need to create and xml config file which register the bean(interface)
with
its implimentation.
Spring.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.0.xsd">
<bean id="SpringBean" class="firstspringprogram.bean.SpringBeanImpl">
</bean>
</beans>
Now
you have done with it, just compile the program.
The
output should be like this -
Output
from Spring Bean:
Thank
You for Calling Me …
Thanks
No comments:
Post a Comment