• [原]spring学习笔记6.补遗3Scope


          Bean的作用范围scope

    Spring配置文件中的<bean>标签可以指定bean的作用范围

    利用<bean>标签中的scope属性来指定

    scope值:

    1、 singleton单例:每次取出的bean都是同一个bean。默认就是这个

    2、 prototype原型:每次取的bean时,都会重新创建一个新的bean

    3、  request

    4、  session

    5、 globalsession

    实例:

      <bean id="u" class="com.sxt.dao.impl.UserDaoImpl" ></bean>

      <bean name="userService" class="com.sxt.service.UserService" scope="prototype">

        <property name="userDao" ref="u"/>    

      </bean>

    注意:只有springweb框架结合时才会使用request/session/globalsession,但也非常少用,因为其它框架已经有功能非常强大的scope(例如:strutsscope)

    如测试scope singleton

             public void testAdd() throws Exception {

                       ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");

    //iduserServicebean的对象两次,结果发现他们的引用地址相同.

                       UserService service = (UserService)ctx.getBean("userService");

                       UserService service2 = (UserService)ctx.getBean("userService");

                       System.out.println(service == service2);  //打印true , 说明每次取的是同一个对象

                       User u = new User();

                       u.setUsername("zhangsan");

                       u.setPassword("zhangsan");

                       service.add(u);

                                                                                                                                                                                                      }

    如测试scope prototype

    用以上同一个测试代码:

    打印出来就是false

  • 相关阅读:
    深入探究Spark -- 了解Executor和参数配置
    深入探究Spark -- Cluster Manger部署(最常用为YARN实现Task Scheduler)
    深入探究Spark -- 最复杂的Shuffle
    深入探究Spark -- 调度器Scheduler
    深入探究Spark -- RDD详解
    深入探究Spark -- 基本组成
    Spark core基础 -- 基本架构和RDD
    Hadoop基础总结(各组件特性)
    Java基础总结
    选做Lintcode分类训练
  • 原文地址:https://www.cnblogs.com/redcoatjk/p/3562371.html
Copyright © 2020-2023  润新知