文件结构:

Java Spring Tutorial -- Singleton and Prototype Bean Scopes_System


NumberGenerator.java

package com.zxl.spring;

import java.util.concurrent.atomic.AtomicInteger;

public class NumberGenerator {
	private static AtomicInteger uniqueNumber =new AtomicInteger(1000);
	public static int getUniqueNumber(){
		return uniqueNumber.incrementAndGet();
	}
}



PrototypeBean.java

package com.zxl.spring;

public class PrototypeBean {
	private int id;
	public PrototypeBean(){
		id=NumberGenerator.getUniqueNumber();
	}

	public int getId() {
		return id;
	}
	
	
}



SingletonBean.java

package com.zxl.spring;

public class SingletonBean {
	private int id;
	public SingletonBean(){
		id=NumberGenerator.getUniqueNumber();
	}
	public int getId() {
		return id;
	}
}



SpringApp05.java

package com.zxl.spring;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringApp05 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("SpringBeans.xml");
		System.out.println("------ singleton bean-------");
		SingletonBean singletonBean=(SingletonBean)context.getBean("singletonBean");
		System.out.println("id: "+singletonBean.getId());
		singletonBean=(SingletonBean) context.getBean("singletonBean");
		System.out.println("id: "+singletonBean.getId());
		singletonBean=(SingletonBean) context.getBean("singletonBean");
		System.out.println("id: "+singletonBean.getId());
		
		
		System.out.println("------ prototype bean-------");
		PrototypeBean prototypeBean =(PrototypeBean)context.getBean("prototypeBean");
		System.out.println("id: "+prototypeBean.getId());
		prototypeBean=(PrototypeBean) context.getBean("prototypeBean");
		System.out.println("id: "+prototypeBean.getId());
		prototypeBean=(PrototypeBean) context.getBean("prototypeBean");
		System.out.println("id: "+prototypeBean.getId());
		context.close();
	}

}



SpringBeans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://www.springframework.org/schema/beans"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
	<bean id="prototypeBean" class="com.zxl.spring.PrototypeBean" scope="prototype" />
	<bean id="singletonBean" class="com.zxl.spring.SingletonBean" scope="singleton" />
	
		
</beans>



Java Spring Tutorial -- Singleton and Prototype Bean Scopes_System_02