[题目]web
Spring中定义bean的做用域时,使用singleton和prototype有何区别?面试
[正确答案]spring
singleton做用域:当把一个Bean定义设置为singleton做用域时,Spring IoC容器中只会存在一个共享的Bean实例,而且全部对Bean的请求(将其注入到另外一个Bean中,或者以程序的方式调用容器的getBean()方法),只要id与该Bean定义相匹配,则只会返回该Bean的同一实例,能够理解为单例模式。session
prototype做用域:prototype做用域的Bean会致使在每次对该Bean请求时都会建立一个新的Bean实例。框架
[面试技术点]测试
Spring bean定义的做用域概念。prototype
[解读]code
小博老师用一个简单的例子说明singleton与prototype的区别。对象
好比有一个User类定义以下:作用域
Spring配置文件中bean的定义以下:
测试用例代码以下:
执行结果为:
User is initialized.
若是把bean的scope修改成prototype:
再次运行测试用例,结果为:
User is initialized.
User is initialized.
从上面的例子能够看出,当bean的scope配置为singleton的时候,经过spring context获取bean的实例,只会初始化一次。也就说明singletone是单例模式。
当bean的scope配置为prototype时,经过spring context获取bean的实例,每次都会初始化,也就是说每次都新建了一个对象。
[扩展]
Spring框架支持如下五种bean的做用域:
singleton: bean在每一个Spring IoC 容器中只有一个实例。
prototype:一个bean的定义能够有多个实例。
request:每次http请求都会建立一个bean,该做用域仅在基于web的Spring ApplicationContext情形下有效。
session:在一个HTTP Session中,一个bean定义对应一个实例。该做用域仅在基于web的Spring ApplicationContext情形下有效。
global-session:在一个全局的HTTP Session中,一个bean定义对应一个实例。该做用域仅在基于web的Spring ApplicationContext情形下有效。
缺省的Spring bean 的做用域是singleton。