在一個bean的配置裏面能夠指定一個屬性Scope,也就是bean的範圍,bean的生命週期。java
Scope可取的值5種:singleton(默認)、prototype、request、session、global sessionweb
其中最經常使用的就是:singleton和prototype,其餘的三個是和web相關的,不多使用。session
singleton:也就是單例模式。表示這個bean是單例模式,每次獲取都是同一個beanapp
prototype:多例模式,也就是每次獲取的都是一個新對象,使用場景:在action上須要設置爲prototype測試
例如:user這個bean,默認的Scope屬性咱們沒有配置,也就是singleton模式spa
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.net
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=prototypeprototype
在<bean>上加入scope=prototype以後。code
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,結果爲falsexml
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
}
|