spring 学习(三)Bean的作用域

Bean的作用域有如下几个:
(1)、singleton:单例,在一个Bean容器中只存在一份
(2)、prototype:每次使用创建新的实例,destroy方式不生效
(3)、request:每次http请求创建一个实例且仅在当前request内有效
(4)、session:每次http请求创建,当前session内有效
(5)、global session:基于portlet的web中有效(portlet定义了global session),如果在web中,跟session一样。

(一)作用域:singleton
1、我们写个测试案例:我们新建一个BeanScope.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"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd" >

        <bean id = "beanScope"  class = "com.yuna.scope.BeanScope" scope="singleton">
        </bean>
 </beans>

2、新建BeanScope类,只有个简单的输出方法,我们可以根据hashcode的值来看看,在不同的作用域中其值有什么不一样

public class BeanScope {

    public void say() {
        System.out.println("hashcode 是不是一致呢:" + this.hashCode());
    }
}

3、写个测试类TestBeanScope

public class TestBeanScope extends UnitTestBase{

    public TestBeanScope() {
        super("classpath:BeanScope.xml");
    }

    @Test
    public void testSingleton() {

        BeanScope bScope = super.getBean("beanScope");
        bScope.say();
        BeanScope bScope2 = super.getBean("beanScope");
        bScope2.say();
    }
//我们测试scope="singleton"时,可以看出bScope.say()和bScope2.say()打印的值是一致的,但是,若是写两个测试方法,一个是 testSingleton() ,一个是 testSingleton2(),此时他们打印的 bScope.say()方法打印的hashcode值是不一样的,这是由于单元测试的原因,单元测试时每个方法执行前会先调用UnitTestBase类的before()方法,然后再执行destory()方法
}

(二)作用域:prototype
1、我们将刚才的BeanScope.xml中的scope改成prototype

<?xml version="1.0" encoding="UTF-8"?>
<beans  xmlns="http://www.springframework.org/schema/beans" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd" >

        <!--作用域是singleton  -->
       <!--  <bean id = "beanScope"  class = "com.yuna.scope.BeanScope" scope="singleton">
        </bean> -->

        <!--作用域是prototype  -->
         <bean id = "beanScope"  class = "com.yuna.scope.BeanScope" scope="prototype">
        </bean>
 </beans>

2、在测试类中写个testPrototype方法,然后一起运行,可以看到打印的hashcode值是不一样的

@Test
    public void testPrototype() {
        BeanScope bScope = super.getBean("beanScope");
        bScope.say();
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值