美文网首页
Spring作用域

Spring作用域

作者: YoungJadeStone | 来源:发表于2020-05-17 05:50 被阅读0次

当我们在定义Bean的时候,不仅可以设置它的值,而且可以设置它的作用域(scope)。

scope种类

Spring bean的scope有这么几种:

  • singleton: (Default) Single bean definition for a single object instance per container. 在这个spring container里面,这个bean只有一个实例。这种bean主要用在stateless beans的情况。(个人理解:像是设置一些静态常量,可以全局使用。)

  • prototype: Single bean definition for multiple instances. 每次我们用ApplicationContext去call getBean()的时候,spring container就会创建一个新的实例。所以每个request都会创建一个新的这个bean的实例。这种bean主要用在stateful beans的情况。(个人理解:在server-client模型中,server要处理从client来的很多request,而且server希望知道每个request的信息,像是request的context,所以需要prototype。)

  • request: Single bean definition for a single HTTP request.

  • session: Single bean definition for the HTTP session.

  • globalSession: Single bean definition for the global HTTP session. Typically only valid when used in portlet context.

  • application: Single bean definition for the entire application bound to the lifecycle of a ServletContext

在多数情况,我们只会使用singleton和prototype两种scope,如果在spring配置文件内未指定scope属性,默认为singleton。Request, session and application只有在the context of a web-aware ApplicationContext(web应用)才有效。

scope设置

可以用@scope来设置。


reference: https://memorynotfound.com/spring-bean-scopes-singleton-vs-prototype/

相关文章

  • SPRING BEAN的基础

    一、SPRING BEAN的定义: 二、SPRING BEAN的作用域: 作用域例子: your msg :p...

  • Spring

    Spring Bean 作用域 Spring 3 中为 Bean 定义了 5 中作用域分别为 singleton(...

  • Spring Bean 作用域

    原文 :一文读懂Spring Bean作用域 - RelaxHeart网 Spring Bean的几种作用域 Sp...

  • Spring Bean的生命周期

    Spring 容器可以管理 singleton 作用域 Bean 的生命周期,在此作用域下,Spring 能够精确...

  • 2.SpringIOC的Scope配置

    如何使用spring的作用域? 在spring2.0之前bean只有2种作用域即:singleton(单例)、no...

  • Spring IOC原理(二)

    Spring作用域 Spring 3 中为Bean 定义了5 中作用域,分别为singleton(单例)、prot...

  • spring详解(二)

    ③容器中bean的作用域: |作用域|描述||---|---||singleton|单例模式,在整个Spring ...

  • Spring_04_Bean的作用域

    Bean的作用域  当在Spring中定义个bean时,你必须声明bean的作用域选项.例如,为了强制Spring...

  • spring bean的作用域

    Bean的作用域参考:spring FrameWork官方文档spring4.x中官方有7中作用域,如果使用的是a...

  • spring bean的作用域配置及相关问题

    一、spring的作用域分五种: 1.singleton: bean的默认作用域,spring容器内存在一个实例。...

网友评论

      本文标题:Spring作用域

      本文链接:https://www.haomeiwen.com/subject/clfjohtx.html