Spring学习心得(4)-- Spring容器创建对象的单/多例

来源:互联网 发布:魅族note6网络频段 编辑:程序博客网 时间:2024/05/24 03:22

在前面,我们讨论到了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 

大致内容是说: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容器才创建相应的对象

创建时机和scope的结合

Scope为prototype,lazy-init为true

       在context.getBean时创建对象

Scopse为prototype,lazy-init为false

       在context.getBean时创建对象,lazy-init为false失效

当scpose为prototype时,始终在context.getBean时创建对象

Scopse为singleton

       是默认情况



0 0