scope的取值对spring容器创建对象的单/多例的影响

在前面,我们讨论到了spring容器创建对象的3种方式以及spring容器创建对象的时机,那么我们现在来讨论一下spring容器创建对象的单/多例
那么

怎样判断spring容器创建的对象是单例还是多例呢?

public class testHelloSpring {
    /**
     * 判断spring容器创建的对象是单例/还是多例
     */
    @Test
    public void test1(){
        //启动spring容器
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
        //得到helloSpring对象
        helloSpring helloSpring=(helloSpring) applicationContext.getBean("hello");
        helloSpring helloSpring2=(helloSpring) applicationContext.getBean("hello");
        //对比这两个引用对象的hashcode
        System.out.println(helloSpring);
        System.out.println(helloSpring2);
    }
}

首先,我们要先用2个引用对象得到这个对象,判断它们的hashcode.
运行之后的结果为:
这里写图片描述
我们可以看到,两个引用对象输出的hashCode是一样的,那么就是说spring容器默认创建的对象是单例的。

那么如何设置spring产生的对象为多例呢?

首先spring的配置文件的bean中有一个scope属性,其取值为:singleton/prototype/request/session
当我们鼠标移动到scope的时候,出现了下面一行的内容:

The scope of this bean: typically "singleton" (one shared instance, which will be returned by all 
 calls to getBean with the given id), or "prototype" (independent instance resulting from each call 
 to getBean). Default is "singleton". Singletons are most commonly used, and are ideal for multi-
 threaded service objects. Further scopes, such as "request" or "session", might be supported by 
 extended bean factories (e.g. in a web environment). Note: This attribute will not be inherited by 
 child bean definitions. Hence, it needs to be specified per concrete bean definition. Inner bean 
 definitions inherit the singleton status of their containing bean definition, unless explicitly 
 specified: The inner bean will be a singleton if the containing bean is a singleton, and a prototype 
 if the containing bean has any other scope.

大致内容是说:singleton是默认的取值,当客户端调用该对象的时候,返回的时一个单利的对象。而prototype返回的是一个多例的对象,在每一次调用的时候,都返回一个新的对象。而request/session等取值,是在web环境下使用。

还有一个特点就是,当我们使用了scope的值为prototype的时候,spring创建对象的时机也会变成当我们调用某个对象的时候才创建相应的对象
配置文件中的代码为:

    <bean class="cn.ansel.domain.helloSpring" id="hello" lazy-init="true" scope="prototype"></bean>

测试类的代码为:

public class testHelloSpring {
    /**
     * 测试配置文件中scope的取值为prototype时,对象的创建时机
     */
    @Test
    public void test1(){
        //启动spring容器
        ApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml");
        System.out.println(" scope is prototype");
        //得到helloSpring对象
        helloSpring helloSpring=(helloSpring) applicationContext.getBean("hello");
    }
}

运行结果为:
这里写图片描述
由上可以得到,当scope取值为prototype的时候,客户端在调用某个类的时候,spring容器才创建相应的对象

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值