• 作者:谁知道水烫不烫
  • 分类: java

Spring框架支持六个作用域,其中四个只有在Web中才能用到,在此我们只说明前两种作用域。

下面是所有的六种作用域:

Scope Description

singleton

(Default) Scopes a single bean definition to a single object instance for each Spring IoC container.

prototype

Scopes a single bean definition to any number of object instances.

request

Scopes a single bean definition to the lifecycle of a single HTTP request. That is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring .ApplicationContext

session

Scopes a single bean definition to the lifecycle of an HTTP . Only valid in the context of a web-aware Spring .SessionApplicationContext

application

Scopes a single bean definition to the lifecycle of a . Only valid in the context of a web-aware Spring .ServletContextApplicationContext

websocket

Scopes a single bean definition to the lifecycle of a . Only valid in the context of a web-aware Spring .WebSocketApplicationContext

这里我们对前两种singleton(单例)和prototype(原型进行学习)。

一、singleton

单例作用域是Spring框架的默认作用域。官方对它的说明是这样的:

仅管理单例 Bean 的一个共享实例,并且所有对 ID 或 ID 与该 Bean 定义匹配的 Bean 的请求都会导致 Spring 容器返回该特定 Bean 实例。

换句话说,当你定义一个bean定义并且它的范围是一个单例时,Spring IoC容器只创建由该bean定义定义的对象的一个实例。此单个实例存储在此类单例 Bean 的缓存中,并且对该

命名 Bean 的所有后续请求和引用都将返回缓存的对象。下图显示了单例作用域的工作原理:

 下面是官方给出的单例的实例:

<bean id="accountService" class="com.something.DefaultAccountService"/>
<!-- the following is equivalent, though redundant (singleton scope is the default) -->
<bean id="accountService" class="com.something.DefaultAccountService" scope="singleton"/>

上面两段代码的效果是完全一样的,由于默认是单例模式,所以scope="singleton"这样显性地展示出来并非必要的。

下面我们对单例模式进行一个测试,看它是否是同一个对象的实例。

<bean id="student" class="com.jms.pojo.Student">

 

 由此我们可以确认这是同一个实例。

二、prototype

Bean 部署的非单例原型范围会导致每次对特定 Bean 发出请求时都会创建新的 Bean 实例。也就是说,将 Bean 注入到另一个 Bean 中,或者您通过容器上的方法调用来请求它。通常,应将原型作用域用于所有有状态 Bean,将单例作用域用于无状态 Bean。

 下面是官方给出的原型作用域的实例:

<bean id="accountService" class="com.something.DefaultAccountService" scope="prototype"/>

我们接下来对原型作用域进行测试:

<bean id="student" class="com.jms.pojo.Student" scope="prototype">

 

 可以看到使用原型作用域后两个对象不再是一个实例。

 

(本文仅作个人学习记录用,如有纰漏敬请指正)

转载自: https://www.cnblogs.com/jmsstudy/p/16726406.html