7.5.2 The prototype scope

The non-singleton, prototype scope of bean deployment results in the creation of a new bean instance every time a request for that specific bean is made. That is, the bean is injected into another bean or you request it through a getBean() method call on the container. As a rule, use the prototype scope for all stateful beans and the singleton scope for stateless beans.

非单例,原型域的部署结果是每一次请求都会创建一个新的bean实例.这也就是说,这个bean被注入到其他bean中或你去请求它都会通过调用getBean()方法.有一个规则,对于有状态的beans使用原型域,对于无状态的beans使用单例域.

The following diagram illustrates the Spring prototype scope. 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的原型域.一个数据访问对象通常不会配置成原型,因为通常DAO不会保持任何会话状态;作者只是偷个懒,重新用了单例的图表.

prototype

The following example defines a bean as a prototype in XML:

下面的例子是在XML中定义一个原型bean:

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

In contrast to the other scopes, Spring does not manage the complete lifecycle of a prototype bean: the container instantiates, configures, and otherwise assembles a prototype object, and hands it to the client, with no further record of that prototype instance. Thus, although initialization lifecycle callback methods are called on all objects regardless of scope, in the case of prototypes, configured destruction lifecycle callbacks are not called. The client code must clean up prototype-scoped objects and release expensive resources that the prototype bean(s) are holding. To get the Spring container to release resources held by prototype-scoped beans, try using a custom bean post-processor, which holds a reference to beans that need to be cleaned up.

与其他域相比,Spring不会管理一个原型bean的整个生命周期:容器实例化,配置还有装配一个原型对象,然后处理它后给客户端,之后就没有原型实例的进一步记录了.因此,尽管初始化生命周期回调方法在所有的对象上被调用,不管是什么域的,在原型的情况下,被配置为销毁生命周期回调不被调用.客户端代码必须清理原型域对象和释放昂贵的资源类维持原型bean(s).为了让Spring容器释放原型域beans所拥有的资源,尝试使用一个定制bean post-processor,它有一个需要被清理的beans的引用.

In some respects, the Spring container’s role in regard to a prototype-scoped bean is a replacement for the Java new operator. All lifecycle management past that point must be handled by the client. (For details on the lifecycle of a bean in the Spring container, see Section 7.6.1, “Lifecycle callbacks”.)

在一些方面,Spring容器的原型域中的bean代替了Java的new操作符.所有生命周期管理经过这个点时都必须通过客户端处理.(关于bean的生命周期更加详细的细节请看Section 7.6.1, “Lifecycle callbacks”.)

扫描二维码关注公众号,回复: 2544441 查看本文章

猜你喜欢

转载自blog.csdn.net/weixin_41648566/article/details/81110188