Wednesday, December 23, 2009

Spring Easy Example with Screen shots

Spring Tutorial By Murthy

Writing a Simple Spring Application :
I am explaining this application using MyEclipse IDE. Better to use MyEclipse because it has inbuilt support for Spring Framework. If you are using Eclipse ,you have to install plugins.


1) File->New->JavaProject


Then give project name as your wish. I gave project name as Project12 and click on Finish button.



2) Right click on the Project12 and follow as follows:

New-->Package-->give any name what you want.
For ex: com.companyname.projectname.iocmodule
Then click on Finish button.

3) In order to add Spring capabilities to our application we have to add Spring container. To do this follow the below steps:

Right click on the project and then Click on MyEclipse-->Add Spring Capabilities-->Select Spring 2.5 core libraries Checkbox.



4) Then one applicationContext.xml will be added in our project src folder. Just rename dat file to anyname.xml.

5) Then create a class under our package and provide that name as EmployeeContent.
Write the following code in this class as follows:

package com.companyname.projectname.iocmodule;

public class EmployeeContent {
private String empname;
private String city;
private String country;
public EmployeeContent(){
System.out.println("Employee Content created");
}
public String getEmpname() {
return empname;
}
public void setEmpname(String empname) {
this.empname = empname;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}

6) Edit anyname.xml file and add the following code:





hyderabad


india


Murthy




7) Similarly we have to write another main method class in our package as follows:
Name this class as TestClient

package com.companyname.projectname.iocmodule;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

public class TestClient {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BeanFactory container=new XmlBeanFactory(new ClassPathResource("anyname.xml"));
System.out.println("container created");
Object o=container.getBean("empbean");
EmployeeContent ec=(EmployeeContent)o;
System.out.println(ec.getCity());
System.out.println(ec.getCountry());
System.out.println(ec.getEmpname());
}

}


8) All our coding part is over. Then just Run it ,you will get the output as follows:

Employee Content created
hyderabad
india
Murthy


If you have any doubts send reply to me. Plz send feedback, your feedback is very useful for me.

Thanks&Regards
Murthy
murthy.mca53@gmail.com

If anybody want more theory and programs just send a message.