Skip to main content

Creating First Spring Program

This project is developed using Eclipse IDE.

You need to add Spring jar file:
Click Here to Download Spring jar

Employee.java

1
2
3
4
5
6
7
8
9
10
11
12
13
package org.training;
 
public class Employee 
{
 
	public void Test()
	{
 
		System.out.println("Test Method is called");
 
	}
 
}

TestMain.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package org.training;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
 
public class TestMain 
{
	public static void main(String[] args)
	{
		System.out.println("**********************");
		ApplicationContext context=new ClassPathXmlApplicationContext("Spring-config.xml");
		Employee e=	(Employee)context.getBean("emp");
	        e.Test();
	        System.out.println("***********************");
	}
}

Spring-config.xml

1
2
3
4
5
6
7
8
9
10
11
12
<?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:p="http://www.springframework.org/schema/p"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
               http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
 
<bean id="emp" class="org.training.Employee"/>  
 
 
</beans>

Output:
Project Structure

Here we Use Application Context object to get Object of Employee.
You can also use Bean factory to do the same but Application Context is more efficient way to do it.
TestMain2.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package org.training;
 
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
 
public class TestMain2 
{
 
 
	public static void main(String[] args)
	{
 
		System.out.println("**********************");
 
		BeanFactory factory=new XmlBeanFactory(new ClassPathResource("Spring-config.xml"));
 
		Employee e=(Employee) factory.getBean("emp");
 
	        e.Test();
 
	        System.out.println("***********************");
 
	}
}

Output: