spring Bean Instantiation Modes

    By default, all beans in Spring are singletons. This means that Spring maintains a single instance of the bean, all dependent objects use the same instance, and all calls to BeanFactory.getBean() return the same instance
有三种方式可以改变bean生成的不是单例的,在bean 的节点属性scope指定,默认值是:"singleton".可以以三种任意的值:"prototype","request","session"代替.

prototype含义是:在每次调用BeanFactory.getBean()方法返回的是一个新的对象

request含义是:在每一次http请求调用BeanFactory.getBean()方法返回一个新的对象,如果是同一个http请求,返回的是同一个对象,

session含义是:正像request一样,只是范围不同,一个是请求,一个是会话,因此,在同一个http session中获得的bean是同一个实例.



示例:

配置spring-bean.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" class="java.lang.String" scope="singleton">
<constructor-arg type="java.lang.String" value="Singleton"/>
</bean>
<bean id="prototypeMe" class="java.lang.String" scope="prototype">
<constructor-arg type="java.lang.String" value="Prototype"/>
</bean>
</beans>



代码测试:

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/srping-bean.xml"));
compare(factory, "singleMe");
compare(factory, "prototypeMe");
}
}

输出结果是:

Bean b1=Singleton

Same? true
Equal? true
Bean b1=Prototype
Same? false
Equal? true

 

你可能感兴趣的:(spring,bean,xml,prototype)