There are following some steps to create Spring application in MyEclipse
1 Create the Java Project
Go to File menu - New - project - Java Project. Write the project
name e.g. testspring - Finish. Now the java project is created.
2 Add spring capabilities
Go to Myeclipse menu - Project Capabilities - Add spring capabilities -
Finish. Now the spring jar files will be added. For the simple application
we need only core library i.e. selected by default.
3 Create Java class
To create the java class, Right click on src - New - class - Write the class
name e.g. employee - finish. Write the following code:
package com.test;
public class employee {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void display(){
System.out.println("HCL: "+name);
} }
4 Create the xml file
In case of myeclipse IDE, you don't need to create the xml file as myeclipse
does this for yourselves. Open the applicationContext.xml file, and write
the following code:
<?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="employeebean" class="com.test.employee">
<property name="name" value="Amit Sharma"></property>
</bean>
</beans>
5 Create the test class
Create the java class e.g. Test. Here we are getting the object of employee
class from the IOC container using the getBean() method of BeanFactory.
package com.test;
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 Test {
public static void main(String[] args) {
Resource resource=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(resource);
employee emp=(employee)factory.getBean("employeebean");
emp.display();
} }
The Resource object represents the information of applicationContext.xml file. The Resource is the interface and the ClassPathResource is the implementation class of the Reource interface. The BeanFactory is responsible to return the bean. The XmlBeanFactory is the implementation class of the BeanFactory.
6 Now run the Test class: You will get the output
HCL: Amit Sharma