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

  • 相关阅读:
    Caused by: 元素类型为 "package" 的内容必须匹配 "(result-types?,interceptors?,default-interceptor-ref?,default-action-ref?,default-class-ref?,global-results?,global-exception-mappings?,action*)"
    web.xml中的url-pattern映射规则
    基于Bootstrap的超酷jQuery开关按钮插件
    jQuery实例-记住登录信息
    java对cookie的操作
    jQuery插件 -- Cookie插件jquery.cookie.js(转)
    分布式系统架构师必须要考虑的四个方面
    初八回杭州的路上
    再说项目经历
    写项目经历的注意事项
  • 原文地址:https://www.cnblogs.com/redcoatjk/p/3562371.html
Copyright © 2011-2022 走看看