本文介绍了单例设计模式与 Spring 容器中的单例 bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知,在 Spring 容器中,默认情况下我们有 bean 作为单例,如果我们有一个基于 Spring 框架的 Web 应用程序,那么在这种情况下,我们是否真的需要实现单例设计模式来保存全局数据,而不是仅仅创建一个豆过春.

As we all know we have beans as singleton by default in Spring container and if we have a web application based on Spring framework then in that case do we really need to implement Singleton design pattern to hold global data rather than just creating a bean through spring.

如果我无法解释我真正想问的是什么,请多多包涵.

Please bear with me if I'm not able to explain what I actually meant to ask.

推荐答案

Spring 中的单例 bean 和单例模式有很大的不同.单例模式表示,每个类加载器只会创建一个特定类的一个实例.

A singleton bean in Spring and the singleton pattern are quite different. Singleton pattern says that one and only one instance of a particular class will ever be created per classloader.

Spring 单例的范围被描述为每个容器每个 bean".它是 bean 定义的范围到每个 Spring IoC 容器的单个对象实例.Spring 中的默认范围是 Singleton.

The scope of a Spring singleton is described as "per container per bean". It is the scope of bean definition to a single object instance per Spring IoC container. The default scope in Spring is Singleton.

即使默认范围是单例,您也可以通过指定 <bean ../> 元素的 scope 属性来更改 bean 的范围.

Even though the default scope is singleton, you can change the scope of bean by specifying the scope attribute of <bean ../> element.

<bean id=".." class=".." scope="prototype" />

这篇关于单例设计模式与 Spring 容器中的单例 bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 07:17