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

  • 相关阅读:
    高斯消元(模板及bitset优化异或方程)
    dsu on tree
    拉格朗日插值
    [CF] CF900D Unusual Sequences
    【模板】Polya 定理
    Min-25筛学习笔记
    [CF] CF156C Cipher
    基于 Flink + Kafka 的广告实时数据分析建设与实践
    开源中国【面经】Java后台开发
    spring boot中连接数据库报错500(mybatis)
  • 原文地址:https://www.cnblogs.com/redcoatjk/p/3562371.html
Copyright © 2011-2022 走看看