简单了解spring bean作用域属性singleton和prototype的区别

这篇文章主要介绍了简单了解spring bean作用域属性singleton和prototype的区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

1.singleton

当一个bean的作用域设置为singleton, 那么Spring IOC容器中只会存在一个共享的bean实例,并且所有对bean的请求,只要id与该bean定义相匹配,则只会返回bean的同一实例。

换言之,当把一个bean定义设置为singleton作用域时,Spring IOC容器只会创建该bean定义的唯一实例。这个单一实例会被存储到单例缓存(singleton cache)中,并且所有针对该bean的后续请求和引用都将返回被缓存的对象实例,这里要注意的是singleton作用域和GOF设计模式中的单例是完全不同的,单例设计模式表示一个ClassLoader中只有一个class存在,而这里的singleton则表示一个容器对应一个bean,也就是说当一个bean被标识为singleton时候,spring的IOC容器中只会存在一个该bean。

applicationContextER.xml:

  <!--Spring bean作用域-->
  <bean id="get_date" class="java.util.Date" scope="singleton"/>

测试代码:

public class GetDate {
  public static void main(String[] args){
    //获取应用程序上下文接口
    ApplicationContext apl = new ClassPathXmlApplicationContext("applicationContextER.xml");
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
      //反复调用getBean来查看时间
      Date date = (Date) apl.getBean("get_date");
      //休息3秒
      Thread.sleep(1000);
      System.out.println("--------------:" + simpleDateFormat.format(date));

      Date date1 = (Date) apl.getBean("get_date");
      Thread.sleep(1000);
      System.out.println("--------------:" + simpleDateFormat.format(date1));

      Date date2 = (Date) apl.getBean("get_date");
      Thread.sleep(1000);
      System.out.println("--------------:" + simpleDateFormat.format(date2));

      System.out.println("date is date1 : " + (date == date1));
      System.out.println("date1 is date2 : " + (date1 == date2));
    } catch (Exception e) {

    }

  }
}

测试结果:

23:05:04.298 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'get_date'
23:05:04.298 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'get_date'
23:05:04.308 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Eagerly caching bean 'get_date' to allow for resolving potential circular references
23:05:04.309 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'get_date'
23:05:04.310 [main] DEBUG org.springframework.context.support.ClassPathXmlApplicationContext - Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor@3108bc]
23:05:04.310 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'lifecycleProcessor'
23:05:04.311 [main] DEBUG org.springframework.core.env.PropertySourcesPropertyResolver - Could not find key 'spring.liveBeansView.mbeanDomain' in any property source
23:05:04.316 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'get_date'
--------------:2019-12-21 23:05:04
23:05:05.320 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'get_date'
--------------:2019-12-21 23:05:04
23:05:06.324 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'get_date'
--------------:2019-12-21 23:05:04
date is date1 : true
date1 is date2 : true

从上面的结果可以看出,创建好对象之后,存入了缓存中。后面每次都是获取的对象都是从缓存中获取的,而不是新创建的。所以每次获取的对象都是一样的。

2.prototype

prototype作用域部署的bean,每一次请求(将其注入到另一个bean中,或者以程序的方式调用容器的getBean()方法)都会产生一个新的bean实例,相当与一个new的操作,对于prototype作用域的bean,有一点非常重要,那就是Spring不能对一个prototype bean的整个生命周期负责,容器在初始化、配置、装饰或者是装配完一个prototype实例后,将它交给客户端,随后就对该prototype实例不闻不问了。

不管何种作用域,容器都会调用所有对象的初始化生命周期回调方法,而对prototype而言,任何配置好的析构生命周期回调方法都将不会被调用。清除prototype作用域的对象并释放任何prototype bean所持有的昂贵资源,都是客户端代码的职责。(让Spring容器释放被singleton作用域bean占用资源的一种可行方式是,通过使用bean的后置处理器,该处理器持有要被清除的bean的引用。

applicationContextER.xml:

  <!--Spring bean作用域-->
  <bean id="get_date" class="java.util.Date" scope="prototype"/>

测试结果:

23:01:51.314 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'get_date'
23:01:51.324 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'get_date'
--------------:2019-12-21 23:01:51
23:01:52.329 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'get_date'
23:01:52.329 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'get_date'
--------------:2019-12-21 23:01:52
23:01:53.330 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating instance of bean 'get_date'
23:01:53.331 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Finished creating instance of bean 'get_date'
--------------:2019-12-21 23:01:53
date is date1 : false
date1 is date2 : false

从上面的结果可以看出,每次都是创建一个新对象,所以每次的对象都不一样。

总结:从1和2可以看出,当你需要全局的唯一标示的时候可以用singleton,而且singleton只创建一个对象,系统消耗资源小.但是用singleton可能会有线程安全化的问题,这个时候就需要用到prototype 。考虑并发的问题,建议都用prototype。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Spring实战之Bean的作用域singleton和prototype用法分析

    本文实例讲述了Spring实战之Bean的作用域singleton和prototype用法.分享给大家供大家参考,具体如下: 一 配置 <?xml version="1.0" encoding="GBK"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/

  • spring ioc的简单实例及bean的作用域属性解析

    IoC(Inversion if Control)-控制反转是Spring俩大核心技术之一,IoC一般分为俩种类型:依赖注入(Dependency Injection,简称DI)和依赖查找(Dependency Lookup) 使用示例: 1.新建工程并导入Spring相关jar包. 2.新建数据访问层及业务逻辑层 代码结构: 代码示例: /** * 实体Bean * @author BC * */ public class User { private Integer id; private

  • Spring实战之协调作用域不同步的Bean操作示例

    本文实例讲述了Spring实战之协调作用域不同步的Bean操作.分享给大家供大家参考,具体如下: 一 配置 <?xml version="1.0" encoding="GBK"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xs

  • 浅谈Spring中Bean的作用域、生命周期

    本文主要探究的是关于Bean的作用域.生命周期的相关内容,具体如下. Bean的作用域 Spring 3中为Bean定义了5中作用域,分别为singleton(单例).prototype(原型).request.session和global session,5种作用域说明如下: 1.singleton:单例模式,Spring IoC容器中只会存在一个共享的Bean实例,无论有多少个Bean引用它,始终指向同一对象.Singleton作用域是Spring中的缺省作用域,也可以显示的将Bean定义为

  • 详解Spring中Bean的生命周期和作用域及实现方式

    前言 在applicationContext.xml中配置完bean之后,Bean的声明周期状态有哪些.生命周期的各个阶段可以做什么.在applicationContext.xml配置bean的作用域有哪些.其中各个作用域代表的是什么.适用于什么情况.这篇文章做一个记录. 生命周期 初始化 可以直接查看图片,图片来自Spring Bean Life Cycle 从上图看出,Bean初始化完成包括9个步骤.其中一些步骤包括接口的实现,其中包括BeanNameAware接口,BeanFactoryA

  • JSP 中Spring Bean 的作用域详解

    JSP 中Spring Bean 的作用域详解 Bean元素有一个scope属性,用于定义Bean的作用域,该属性有如下五个值: 1>singleton: 单例模式,在整个spring IOC容器中,单例模式作用域的Bean都将只生成一个实例.一般Spring容器默认Bean的作用域为singleton 2>prototype: 与singleton相反, 每次通过容器的getBean()方法获取该作用域下的Bean时都将产生一个新的Bean实例 3>request: 对于同一次Http

  • 深入了解Spring中Bean的作用域和生命周期

    作用域的种类 Spring 容器在初始化一个 Bean 的实例时,同时会指定该实例的作用域.Spring3 为 Bean 定义了五种作用域,具体如下. 1)singleton 单例模式,使用 singleton 定义的 Bean 在 Spring 容器中只有一个实例,这也是 Bean 默认的作用域. 2)prototype 原型模式,每次通过 Spring 容器获取 prototype 定义的 Bean 时,容器都将创建一个新的 Bean 实例. 3)request 在一次 HTTP 请求中,容

  • Spring实战之Bean的作用域request用法分析

    本文实例讲述了Spring实战之Bean的作用域request用法.分享给大家供大家参考,具体如下: 一 配置 1 applicationContext.xml <?xml version="1.0" encoding="GBK"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframewor

  • 简单了解spring bean作用域属性singleton和prototype的区别

    这篇文章主要介绍了简单了解spring bean作用域属性singleton和prototype的区别,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 1.singleton 当一个bean的作用域设置为singleton, 那么Spring IOC容器中只会存在一个共享的bean实例,并且所有对bean的请求,只要id与该bean定义相匹配,则只会返回bean的同一实例. 换言之,当把一个bean定义设置为singleton作用域时,Sprin

  • Spring Bean作用域与生命周期深入讲解

    目录 1.作用域定义 Bean 的作用域 Bean 的 6 种作用域 单例作用域(singleton)和全局作用域(application)区别 2.设置作用域 3.Bean 原理分析 3.1 Bean(Spring)执行流程 3.2 Bean生命周期 1.作用域定义 限定程序中变量的可用范围叫做作用域,或者说在源代码中定义变量的某个区域就叫做作用域. Bean 的作用域 而 Bean 的作用域是指 Bean 在 Spring 整个框架中的某种行为模式,比如 singleton 单例作用域,就表

  • Spring Bean的属性注入方式

    在spring中bean的属性注入有两种 构造器注入 <bean id="car" class="nwtxxb.di.Car"> <constructor-arg index="0" type="java.lang.String" value="保时捷"></constructor-arg> <constructor-arg index="1"

  • 简单了解Spring Bean常用注解的装配

    这篇文章主要介绍了简单了解Spring Bean常用注解的装配,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 基于注解的装配 在Spring框架中,尽管使用XML配置文件可以很简单地装配Bean,但如果应用中有大量的Bean需要装配,会导致XML配置文件过于庞大,不方便以后的升级与维护,因此更多的时候推荐开发者使用注解(annotation)的方式去装配Bean. 在Spring框架中定义了一系列的注解,下面介绍集中常用的注解. @Compon

  • 简单了解spring bean的循环引用

    看过一次spring公开课,记录一下bean的循环引用问题. 问题: public class IndexService{ @Autowired IndexDao indexDao; } public class IndexDao{ @Autowired IndexService indexService; } 以上的实例中IndexService依赖IndexDao,IndexDao中依赖IndexService. spring在bean的实例化过程: 先去创建IndexDao bean, 1

  • Spring IOC原理补充说明(循环依赖、Bean作用域等)

    前言 通过之前的几篇文章将Spring基于XML配置的IOC原理分析完成,但其中还有一些比较重要的细节没有分析总结,比如循环依赖的解决.作用域的实现原理.BeanPostProcessor的执行时机以及SpringBoot零配置实现原理(@ComponentScan.@Import.@ImportSource.@Bean注解的使用和解析)等等.下面就先来看看循环依赖是怎么解决的,在此之前一定要熟悉整个Bean的实例化过程,本篇只会贴出关键性代码. 正文 循环依赖 首先来看几个问题: 什么是循环依

  • 一文搞懂Spring Bean中的作用域和生命周期

    目录 一.Spring Bean 作用域 singleton(单例) prototype(原型) 小结 二.Spring Bean生命周期 如何关闭容器 生命周期回调 通过接口设置生命周期 通过xml设置生命周期 一.Spring Bean 作用域 常规的 Spring IoC 容器中Bean的作用域有两种:singleton(单例)和prototype(非单例) 注:基于Web的容器还有其他种作用域,在这就不赘述了. singleton(单例) singleton是Spring默认的作用域.当

  • Spring Bean的实例化之属性注入源码剖析过程

    前言 这一章节我们来讨论创建Bean过程中的属性注入,在Spring的IOC容器启动过程中,会把定义的Bean封装成BeanDefinition注册到一个ConcurrentHashMap中,Bean注册完成后,就会对单利的且lazy-init=false 的Bean进行实例化.创建Bean的代码在 AbstractAutowireCapableBeanFactory#doCreateBean 中,当Bean创建成功之后,会调用AbstractAutowireCapableBeanFactory

  • 一文搞懂Spring中的Bean作用域

    目录 概述 Singleton prototype request session application 概述 scope用来声明容器中的对象所应该处的限定场景或者说该对象的存活时间,即容器在对象进入其 相应的scope之前,生成并装配这些对象,在该对象不再处于这些scope的限定之后,容器通常会销毁这些对象. Spring容器bean的作用域类型: singleton:Spring IoC 容器的单个对象实例作用域都默认为singleton prototype:针对声明为拥有prototyp

随机推荐