码迷,mamicode.com
首页 > 编程语言 > 详细

Spring中Bean的生命周期Scope

时间:2015-08-21 17:04:09      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

在一个bean的配置里面可以指定一个属性Scope,也就是bean的范围,bean的生命周期。

Scope可取的值5种:singleton(默认)、prototype、request、session、global session

其中最常用的就是:singleton和prototype,其他的三个是和web相关的,很少使用。

singleton:也就是单例模式。表示这个bean是单例模式,每次获取都是同一个bean

prototype:多例模式,也就是每次获取的都是一个新对象,使用场景:在action上需要设置为prototype


例如:user这个bean,默认的Scope属性我们没有配置,也就是singleton模式

1
2
3
4
5
6
<bean name="user" class="com.fz.entity.User" >
    <property name="id" value="1"></property>
    <property name="username" value="fangzheng"></property>
    <property name="password" value="123456"></property>
    <property name="role" ref="role"></property>
</bean>

测试singleton,结果为true

1
2
3
4
5
6
7
@Test
public void getProperties(){
    ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
    User user1 = (User) ctx.getBean("user");
    User user2 = (User) ctx.getBean("user");
    System.out.println(user1 == user2);//结果为true   
}


添加scope=prototype

在<bean>上加入scope=prototype之后。

1
2
3
4
5
6
<bean name="user" class="com.fz.entity.User" scope="prototype">
    <property name="id" value="1"></property>
    <property name="username" value="fangzheng"></property>
    <property name="password" value="123456"></property>
    <property name="role" ref="role"></property>
</bean>

测试prototype,结果为false

1
2
3
4
5
6
7
@Test
public void getProperties(){
    ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
    User user1 = (User) ctx.getBean("user");
    User user2 = (User) ctx.getBean("user");
    System.out.println(user1 == user2);//结果为false
}










Spring中Bean的生命周期Scope

标签:

原文地址:http://www.cnblogs.com/meet/p/4748354.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!