spring1 (1)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

Spring example

Student.java

package spring1;
public class Student
{
private String name;

public String getName()


{
return name;
}

public void setName(String name)


{
this.name = name;
}

public void displayInfo()


{
System.out.println("Hello: "+name);
}
}

applicationContext.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"
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="studentbean" class="spring1.Student">
<property name="name" value="Nikitha"></property>
</bean>
</beans>
Test.java

package spring1;
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=newClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(resource);
Student student=(Student)factory.getBean("studentbean");
student.displayInfo();
}
}

OUTPUT
STEPS:
1 Create the bean class
 Create a bean class which contains getters and setters method.

2 Create the xml file to provide the values for bean class

 The bean element is used to define the bean for the given class.
 The property element of bean specifies the property of the Student
class
 The value specified in the property element will be set in the
Student class object

3 Create the java file to invoke the bean

 Create the java class to invoke the bean


 getBean() method of BeanFactory is used to get the object of
Student class
 The Resource object represents the information of
applicationContext.xml file.
 The Resource is the interface and the ClassPathResource is the
implementation class of the Resource interface.
 The XmlBeanFactory is the implementation class of the
BeanFactory.
 getBean() is method of BeanFactory interface, which returns the
object of the associated class.

4 Load the spring jar files

jar files required to run this application.

o org.springframework.core-3.0.1.RELEASE-A
o com.springsource.org.apache.commons.logging-1.1.1
o org.springframework.beans-3.0.1.RELEASE-A

Link: https://www.javatpoint.com/src/sp/spcorejars.zip

Unzip the file, and place it java->jre->lib->ext

5 Run the application(cmd)

 Javac -d .Student.java ( compile Student)


 Javac -d .test.java ( compile test)
 Java spring1.test (run)

Call using object


Bean JAVA
(student.java) (test.java)

setter getter

XML

(applicationCont
ext.xml)

You might also like