SpringXML方式配置bean的生存范围Scope
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了SpringXML方式配置bean的生存范围Scope,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1783字,纯文字阅读大概需要3分钟。
内容图文
在一个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
}
|
原文:http://www.cnblogs.com/meet/p/4758195.html
内容总结
以上是互联网集市为您收集整理的SpringXML方式配置bean的生存范围Scope全部内容,希望文章能够帮你解决SpringXML方式配置bean的生存范围Scope所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。