象
Cat:
package com.li.bean;
/**
* @author 李
* @version 1.0
*/
public class Cat {
private Integer id;
private String name;
public Cat() {
System.out.println("Cat() 构造器被执行...");
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
beans.xml:
<!--配置 Cat对象
1.默认情况下,scope属性的值为 "singleton",即ioc容器中只会有一个这样的bean对象
当执行getBean时,返回的是同一个对象
2.如果希望每次使用getBean都返回新的Bean对象,就要把scope的属性设为 prototype
-->
<bean id="cat" class="com.li.bean.Cat">
<property name="id" value="10"/>
<property name="name" value="小花猫"/>
</bean>
测试类:
//测试Scope
@Test
public void testBeanScope() {
ApplicationContext ioc = new ClassPathXmlApplicationContext("beans.xml");
Cat cat1 = ioc.getBean("cat", Cat.class);
Cat cat2 = ioc.getBean("cat", Cat.class);
Cat cat3 = ioc.getBean("cat", Cat.class);
System.out.println("cat1="+cat1);
System.out.println("cat2="+cat2);
System.out.println("cat3="+cat3);
}
输出如下:地址值相同,证明这三个对象引用都指向了同一个对象
例子2-多例对象
现在我们把例子1的cat对象的配置改为scope="prototype"
<bean id="cat" class="com.li.bean.Cat" scope="prototype">
<property name="id" value="10"/>
<property name="name" value="小花猫"/>
</bean>
输出如下:构造器执行了三次,说明创建了三个Cat对象(对象的地址值也不一样)
使用细节:
-
当bean为scope="singleton"(默认值),在启动容器时,就会创建单例对象,并放入singletonObjects集合
-
当bean设置为scope="prototype",即设置为多实例机制后,该bean是在getBean时才创建
-
如果是单例singleton,但又希望在getBean时才创建,可以指定懒加载lazy-init="true" (默认值是false)
-
通常情况下,lazy-init 使用默认值false,因为在开发看来,用空间换时间是值得的,除非有特殊要求。
-
如果scope="prototype",这时你的lazy-init属性值不管设置为什么,都默认为true
因为多例情况下,spring无法知道创建几个对象,因此只有在用到的时候才能创建