bean 的作用域
1、在 Spring 里面,可以设置创建 bean 实例是 单实例还是多实例。
2、在 Spring 里面,默认情况下, bean 是单实例对象。
<?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="person" class="com.lmgd.entity.Person">
<property name="name" value="邓林妹"></property>
<property name="age" value="25"></property>
</bean>
</beans>
@org.junit.Test
public void testIOC() {
ApplicationContext context = new ClassPathXmlApplicationContext("bean4.xml");
Person person1 = context.getBean("person", Person.class);
Person person2 = context.getBean("person", Person.class);
System.out.println(person1);
System.out.println(person2);
}
Spring IOC中 person1 与 person2 内存地址一样,由此可见默认是单例模式(只初始化一次)
如何设置单实例还是多实例?
(1)在 Spring 配置文件 bean 标签里面有属性(scope) 用于设置单实例还是多实例
(2)scope属性值
第一个值 默认值,singleton 表示是单实例对象(只初始化一次)
第二个值 prototype,表示是多实例对象(每次请求都会生成一个新的对象)
<bean id="person" class="com.lmgd.entity.Person" scope="prototype">
<property name="name" value="邓林妹"></property>
<property name="age" value="25"></property>
</bean>
scope属性值设置为 prototype,person对象输出的内存地址不一样:
(3)singleton 和 prototype 区别
第一:singleton 单实例,prototype 多实例
第二:创建对象的时机不一样
1、设置 scope 值是为 singleto 时,加载 Spring 配置文件就会创建单实例对象。
调用如下代码,就会创建单实例对象:
ApplicationContext context = new ClassPathXmlApplicationContext("bean4.xml");
2、设置 scope 值为 prototype 时,不是在加载 Spring 配置文件时候创建对象,而是在调用 getBean() 方法时,创建多实例对象。
其他(了解)
scope 属性值还有 request、session