Spring
First Application
Create
a simple application by using Eclipse IDE.
Steps
are below:
1.
Create the Java project
2.
Add Spring jar files
3.
Create the POJO class
4.
Create the XML file to provide values
5.
Create the execute class
1.
Create the Java project
File
→ New → Java Project (SpringExample01)
2.
Add Spring jar files
These
are the first few libraries need to add the build
path.
*
org.springframework.core-3.0.0.M3.jar
*
org.springframework.beans-3.0.0.M3.jar
*
commons-logging-1.0.4.jar
3.
Create the POJO class
Create
the POJO class inside the package which is under the src
folder.
package
com;
import
java.io.Serializable;
public
class
Student implements
Serializable {
/**
*
*/
private
static
final
long
serialVersionUID
= 1L;
private
String name;
public
String getName() {
return
name;
}
public
void
setName(String name) {
this.name
= name;
}
public
void
displayStudentInfo(){
System.out.println("Student
Name : " + name);
}
}
4.
Create the XML file to provide values
To
create the XML file as per the below steps to avoid the compile time
errors.
1.
Select the desired folder which you are going to locate the XML. (
for this example it is “src” )
2.
Right click the folder → New → “Spring Bean Configuration
File“
3.
Give the file name as “ApplicationContext.xml” and click next
bitton .
4.
Then tick the desired XSD namespace ( for this example it is bean).
5.
Then tick the desired XSD ( for this example it is
spring-beans-3.0.xsd) and click finish button.
6.
Then it create the relevant XML, “ApplicationContext.xml”.
7.
Then add the relevant bean information.
<?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-3.0.xsd">
<bean
id="studentBean"
class="com.Student">
<property
name="name"
value="Sanjeeva
Pathirana"/>
</bean>
</beans>
5.
Create the execute class
package
com;
import
org.springframework.beans.factory.BeanFactory;
import
org.springframework.beans.factory.xml.XmlBeanFactory;
import
org.springframework.core.io.ClassPathResource;
import
org.springframework.core.io.Resource;
public
class
StudentTest {
/**
* @param
args
*/
public
static
void
main(String[] args) {
try{
Resource
resource = new
ClassPathResource("ApplicationContext.xml");
BeanFactory
beanFactory = new
XmlBeanFactory(resource);
Student
student = (Student)beanFactory.getBean("studentBean");
student.displayStudentInfo();
}catch
(Exception e) {
e.printStackTrace();
}
}
}
Out
put as follows.
Aug
25, 2013 8:14:40 PM
org.springframework.beans.factory.xml.XmlBeanDefinitionReader
loadBeanDefinitions
INFO:
Loading XML bean definitions from class path resource
[ApplicationContext.xml]
Student
Name : Sanjeeva Pathirana