Spring Framework

Spring Projects

Spring Project 1

adplus-dvertising
Example of prototype bean
Previous Home Next

Introduction:The prototype bean is the optional bean of the scope attribute that provide the facility to the user create more then one object if you are requested more then one time the prototype bean provide per request new object of same bean.

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.Complex" factory-method="getNumber" scope="singleton"/>
</beans>

Number.java

package org.r4r;
public interface Number {
public void display();
public Number add(Number n);
}

Rational.java

package org.r4r;
import java.util.Scanner;
public class Rational implements Number {
int p,q;
public Rational(int p, int q) {
super();
this.p = p;
this.q = q;
}
public static Number getNumber(){
Scanner in=new Scanner(System.in);
System.out.println("Enter the Numerator part:-");
int p=in.nextInt();
System.out.println("Enter the Denominator part:-");
int q=in.nextInt();
return new Rational(p,q);
}
@Override
public Number add(Number n) {
Rational r=(Rational)n;
int x=this.p*r.q+this.q*r.p;
int y=this.q*r.q;
return new Rational(x,y);
}
@Override
public void display() {
System.out.println(p+"/"+q);
}
}

IocNumberUser.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 IocNumberUser {
public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory f=new XmlBeanFactory(r);
System.out.println("Obtaining numbers n1 & n2 from the IOC Container...");
Number n1=(Number)f.getBean("number");
Number n2=(Number)f.getBean("number");
System.out.println("Number n1 is:");
n1.display();
System.out.println("Number n2 is:");
n2.display();
Number n3=n1.add(n2);
System.out.println("Sum of n1 and n2");
n3.display();
}
}

Output:

Obtaining numbers n1 & n2 from the IOC Container...
Enter the Numerator part:-
6
Enter the Denominator part:-
5
Enter the Numerator part:-
4
Enter the Denominator part:-
8
Number n1 is:
6/5
Number n2 is:
4/8
Sum of n1 and n2
68/40
Previous Home Next