zoukankan      html  css  js  c++  java
  • [原]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

  • 相关阅读:
    Android应用开发学习笔记之事件处理
    [置顶] 炎炎夏日,给你一次极爽的开发体验!——统一开发环境功能升级优化,正式上线V2.0!
    POJ 3468 A Simple Problem with Integers (伸展树区间更新求和操作 , 模板)
    京东商城发现了一枚Bug
    iOS_40_核心动画
    SVN——库合并
    ORACLE 8i 遇到报错:ORA-01631: max # extents (505) reached in table
    HDU 5366:The mook jong 递推
    Linux平台下裸设备的绑定:
    CSP:使用CryptoAPI解码X509证书内容
  • 原文地址:https://www.cnblogs.com/redcoatjk/p/3562371.html
Copyright © 2011-2022 走看看