Spring管理的Bean的作用域

在Spring的Bean中有一个属性scope是用来配置Spring Bean的作用域,它标识Bean的作用域

在Spring 2.0之后默认有五种类型的Bean:

singleton、prototype、request、session、global session(application)

其中,后三种是用于WEB中的Bean对象,下边会有介绍。

PS:需要注意的一点就是,如果Bean没有设置作用域的时候,默认是singleton类型

一、.singleton和.prototype类型

1、singleton

当一个Bean的作用域设置为.singleton,Srping IOC容器中仅仅会存在一个共享的bean实例。

在所有对bean的请求中,只要请求的id与bean的id相同,则他们返回的实例都是同一个。

即当设置为singleton的时候,容器只会创建唯一的一个实例。这个单一实例会被存储到单例缓存(singleton cache)中,并且所有针对该bean的后续请求和引用都将返回被缓存的对象实例。

可以看看如下的代码就应该能够明白了:

这是配置文件beans.xml

<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean" scope="singleton">
</bean>
这是测试文件 SpringTest.java

public void instanceSpring() {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
		PersonService personService1 = (PersonService)ctx.getBean("personService");
		PersonService personService2 = (PersonService)ctx.getBean("personService");
		System.out.println(personService1 == personService2);
}
最后的输出结果是: true 。证明这两个实例是同一个实例。

2、prototype

当bean的作用域设置为prototype的时候,在每次请求bean的时候,Spring IOC容器都会创建一个新的Bean实例。

这是配置文件beans.xml

<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean" scope="prototype">
</bean>

这是测试文件SpringTest.java

public void instanceSpring() {
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
		PersonService personService1 = (PersonService)ctx.getBean("personService");
		PersonService personService2 = (PersonService)ctx.getBean("personService");
		System.out.println(personService1 == personService2);
}

最后的输出结果是: false 。证明这两个Bean实例不是同一个Bean。


二、request、session、global session(application)三种属性暂时还没有接触,等接触的时候会回来完成本篇博文



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值