美文网首页
Spring笔记(二):bean的作用域

Spring笔记(二):bean的作用域

作者: 睿丶清 | 来源:发表于2019-08-15 10:20 被阅读0次

    在bean中配置作用域使用属性scope来设置bean的作用域

    • scope="singleton" 也是bean配置中默认的配置

      bean配置文件代码:

       <bean id="school" class="com.example.demo.entity.School" scope="singleton">
          <property name="schoolName" value="北京大学"></property>
          <property name="schoolAddress" value="北京市海淀区"></property>
      </bean>
      

      java测试代码:

          ApplicationContext ctx = new ClassPathXmlApplicationContext("bean-scop.xml");
      
          School school = (School) ctx.getBean("school");
          School school1 = (School) ctx.getBean("school");
      
          System.out.println(school);
          System.out.println(school1);     
      

      运行结果:

      School被创建
      Disconnected from the target VM, address: '127.0.0.1:51820', transport: 'socket'
      com.example.demo.entity.School@4d5650ae
      com.example.demo.entity.School@4d5650ae
      
      Process finished with exit code 0
      

      从上可以看出bean属性scope为singleton时,容器初始化时会创建实例,该容器中对象的实例有且只有一个

    • scope="prototype"

      bean配置:

       <bean id="school1" class="com.example.demo.entity.School" scope="prototype">
          <property name="schoolName" value="清华大学"></property>
          <property name="schoolAddress" value="北京市海淀区"></property>
      </bean>
      

      java测试代码:

       ApplicationContext ctx = new ClassPathXmlApplicationContext("bean-scop.xml");
      
          School school = (School) ctx.getBean("school1");
          School school1 = (School) ctx.getBean("school1");
      
          System.out.println(school);
          System.out.println(school1);
      
      

      运行结果:

      School被创建
      School被创建
      com.example.demo.entity.School@a38c7fe
      com.example.demo.entity.School@6fdbe764
      

      从运行结果可以看出bean属性scope为prototype时,容器初始化时不会创建bean的实例,只有在调用时才会创建bean的实例;

    • scope="request" 和 scope="session"
      这两个属性都是涉及到与对象,一个是resquest域,两一个是session域

    相关文章

      网友评论

          本文标题:Spring笔记(二):bean的作用域

          本文链接:https://www.haomeiwen.com/subject/wkpajctx.html