zoukankan      html  css  js  c++  java
  • Spring框架(七)—— spring的Bean配置项和作用域

    singleton作用域是默认的作用域,如果想要修改默认作用域可以再<bean>中添加属性scope="pototype"来更改作用域

    global session作用域:应用于多个系统并存的情况下

    案例:

      1、创建一个java project

      2、创建一个包,再包中创建一个BeanScop.java

    package org.bean.example;
    
    public class BeanScope {
        public void save(){
            System.out.println("beanScope:"+this.hashCode());
        }
    }

      3、在创建一个TestBeanScope.java,该类必须继承UnitTestBase.java类(代码:https://www.cnblogs.com/myfaith-feng/p/9211290.html)

    package org.bean.example;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.junit.runners.BlockJUnit4ClassRunner;
    import org.util.test.UnitTestBase;
    
    @RunWith(BlockJUnit4ClassRunner.class)
    public class TestBeanScope extends UnitTestBase{
        
        public TestBeanScope() {
            super("classpath*:spring-ioc.xml");
        }
        
        @Test
        public void test(){
            BeanScope beanScope = super.getBean("beanScope");
            beanScope.save();
            
            BeanScope beanScope1 = super.getBean("beanScope");
            beanScope1.save();
        }
        
        @Test
        public void test2(){
            BeanScope beanScope = super.getBean("beanScope");
            beanScope.save();
        }
        
    }

      4、在项目下创建一个spring-ioc.xml文件

    <?xml version="1.0" encoding="UTF-8"?>
    <beans
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:p="http://www.springframework.org/schema/p"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd" xmlns:tx="http://www.springframework.org/schema/tx">
    
        <bean id="beanScope" class="org.bean.example.BeanScope" scope="singleton"></bean>
    </beans>

      5、配置的scope="singleton"单例作用域,其输出的hashCode是相同的,但是不同容器中其hashCode就会不一样

  • 相关阅读:
    Dynamic CRM 2013学习笔记(四十二)流程5
    Dynamic CRM 2013学习笔记(四十一)流程4
    Dynamic CRM 2013学习笔记(四十)流程3
    Dynamic CRM 2013学习笔记(三十九)流程2
    Dynamic CRM 2013学习笔记(三十八)流程1
    Dynamic CRM 2013学习笔记(三十七)自定义审批流7
    STL
    Step by Step iOS Project In Action
    STL
    STL
  • 原文地址:https://www.cnblogs.com/myfaith-feng/p/9214452.html
Copyright © 2011-2022 走看看