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
@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
}










原文地址:https://www.cnblogs.com/meet/p/4758195.html