3-36使用singletons和prototypes
测试类:
package com.apress.prospring2.ch03.beanfactory;import org.springframework.beans.factory.BeanFactory;import org.springframework.beans.factory.xml.XmlBeanFactory;import org.springframework.core.io.ClassPathResource;/** * @author janm */public class ScopeDemo { private static void compare(final BeanFactory factory, final String beanName) { String b1 = (String)factory.getBean(beanName); String b2 = (String)factory.getBean(beanName); System.out.println("Bean b1=" + b1 + ", b2=" + b2); System.out.println("Same? " + (b1 == b2)); System.out.println("Equal? " + (b1.equals(b2))); } public static void main(String[] args) { BeanFactory factory = new XmlBeanFactory( new ClassPathResource("/META-INF/spring/beanscopedemo1-context.xml")); compare(factory, "singleMe"); compare(factory, "prototypeMe"); }}
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" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="singleMe" scope="singleton"> <constructor-arg type="java.lang.String" value="Singleton -- Jan Machacek"/> </bean> <bean id="prototypeMe" scope="prototype"> <constructor-arg type="java.lang.String" value="Prototype -- Jan Machacek"/> </bean></beans>
结果如下:
Bean b1=Singleton -- Jan Machacek, b2=Singleton -- Jan MachacekSame? trueEqual? trueBean b1=Prototype -- Jan Machacek, b2=Prototype -- Jan MachacekSame? falseEqual? true