Spring Framework

Spring Projects

Spring Project 1

adplus-dvertising
Create Object Example Using Constructor
Previous Home Next

Introduction: This example will used to create object through the constructor and print "This Object is created by constructor".

Technology use to run this source code

  1. Spring 2.5
  2. Eclipse
  3. JDK 1.6
Source Code

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-2.5.xsd">
<bean id="constructorBean" class="org.r4r.ConstructorExample">
<constructor-arg value="This message is generated by Constructor."/>
</bean>
</beans>

ConstructorExample.java

package org.r4r;
public class ConstructorExample {
String message;
public ConstructorExample(String message) {
super();
this.message = message;
}
public void display(){
System.out.println("This message is generated by method.");
System.out.println(message);
}
}

ConstructorTest.java

package org.r4r;
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 ConstructorTest {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory f=new XmlBeanFactory(r);
ConstructorExample e=(ConstructorExample)f.getBean("constructorBean");
e.display();
}
}

Output:

This message is generated by method.

This message is generated by Constructor.

Previous Home Next