Spring Framework

Spring Projects

Spring Project 1

adplus-dvertising
Example of singleton bean
Previous Home Next

Introduction:The singleton bean is the default bean of the scope attribute that provide the facility to the user create only one time object then give the reference of same object if requested by user for this object. If you are not mansion in configuration file this scope attribute give service by default.

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);
}

Complex.java

package org.r4r;
import java.util.Scanner;
public class Complex implements Number {
int r,i;
public Complex(int r, int i) {
super();
this.r = r;
this.i = i;
}
public static Number getNumber(){
Scanner in=new Scanner(System.in);
System.out.println("Enter the rational part:-");
int x=in.nextInt();
System.out.println("Enter the imagenary part:-");
int y=in.nextInt();
return new Complex(x,y);
}
@Override
public Number add(Number n) {
Complex c=(Complex)n;
int x=this.r+c.r;
int y=this.i+c.i;
return new Complex(x,y);
}
@Override
public void display() {
System.out.println(r+"+"+i+"i");
}
}

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 rational part:-
5
Enter the imagenary part:-
6
Number n1 is:
5+6i
Number n2 is:
5+6i
Sum of n1 and n2
10+12i

Previous Home Next