在前面,我们讨论到了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容器才创建相应的对象