SpringXML方式配置bean的生存范围Scope

在一个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
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
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
}










转载于:https://my.oschina.net/u/1045699/blog/786601

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值