Spring Framework

Spring Projects

Spring Project 1

adplus-dvertising
Create Object Example Using Different Class Static Factory
Previous Home Next

Introduction: This example will used to create object through the different class static factory and print "Number you are enter and sum of number which are enter by you".

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="number" class="org.r4r.NumberFactory" factory-method="getNumber"/>
</beans>

NumberFactory.java

package org.r4r;
import java.util.Scanner;
public class NumberFactory {
public static NumberDisplay getNumber(){
Scanner in=new Scanner(System.in);
System.out.println("Enter the first number:-");
int x=in.nextInt();
System.out.println("Enter the second number:-");
int y=in.nextInt();
return new NumberDisplay(x,y);
}
}

NumberDisplay.java

package org.r4r;
public class NumberDisplay {
int a,b;
public NumberDisplay(int a, int b) {
super();
this.a = a;
this.b = b;
}
public void display(){
System.out.println("You are enter first number is:-\t"+a);
System.out.println("You are enter second number is:-\t"+b);
int x=a+b;
System.out.println("Sum of both number is:-"+x);
}
}

NumberTest.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 NumberTest {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory f=new XmlBeanFactory(r);
System.out.println("Obtaining numbers from the IOC Container...");
NumberDisplay n1=(NumberDisplay)f.getBean("number");
n1.display();
}
}

Output:

Obtaining numbers from the IOC Container...
Enter the first number:-
9876
Enter the second number:-
6789
You are enter first number is:- 9876
You are enter second number is:- 6789
Sum of both number is:-16665
Previous Home Next