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










  • 相关阅读:
    layer弹出相册层
    jquery日期和时间的插件精确到秒
    ztree树形菜单的增加删除修改和换图标
    瀑布流插件和模板插件
    使用easyui将json数据生成数据表格
    2013年回顾,2014年计划
    PHP trim去空格函数
    MySql中常用语句
    左右固定,中间自适应布局,中间栏优先加载
    HTML5的全局属性
  • 原文地址:https://www.cnblogs.com/meet/p/4758195.html
Copyright © 2020-2023  润新知