什么时候使用 Spring 原型作用域? [英] When to use Spring prototype scope?

查看:32
本文介绍了什么时候使用 Spring 原型作用域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道我应该什么时候使用 Spring 中的 prototype 作用域?我知道如果请求 bean,singleton 返回相同的对象实例.

I want to know when should I exactly use the prototype scope in Spring? I have understood that singleton returns the same object instance if the bean is requested for.

那我们为什么要考虑prototype?

通过示例进行解释将非常有助于理解对它的需求.

Explanations with examples would help a lot to understand the need for it.

推荐答案

要清楚简单的定义:

  • Prototype scope = 每次注入/查找时都会创建一个新对象.每次都会使用 new SomeBean() .

Singleton scope = 每次注入/查找时都返回相同的对象.这里它会实例化一个 SomeBean 的实例,然后每次都返回它.

Singleton scope = The same object is returned each time it is injected/looked up. Here it will instantiate one instance of SomeBean and then return it each time.

Prototype bean 是在使用时创建的.因此,当您想要有状态的 bean 时,有时强烈需要原型作用域,或者当您不想在 bean 中缓存任何值时.原型 bean 可以与一个会话或某个调用相关联.

Prototype bean is created at the time of usage. So when you would like to have stateful beans there is a strong need sometimes to have prototypes scope or when you don't want to cache any values in beans. Prototype bean can be associated with one session or some call.

示例:

数据访问对象 (DAO) 通常不会配置为原型,因为典型的 DAO 不持有任何会话状态;这位作者更容易重用单例图的核心.

A data access object (DAO) is not typically configured as a prototype, because a typical DAO does not hold any conversational state; it was just easier for this author to reuse the core of the singleton diagram.

这篇关于什么时候使用 Spring 原型作用域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆