gpt4 book ai didi

java - 什么是最佳实践 : Use prototype bean instead of new () operator

转载 作者:搜寻专家 更新时间:2023-11-01 02:57:03 25 4
gpt4 key购买 nike

我试图了解 Spring 原型(prototype) bean 的正确用法是什么。 可能是以下代码示例将帮助您理解我的困境:

List<ClassA> caList = new ArrayList<ClassA>();
for (String name : nameList) {
ClassA ca = new ClassA();

//or Shall I use protypebean, using method lookup I can inject the dependency of ClassA.
// ClassA ca = getPrototypeClassA();

ca.setName(name);
caList.add(ca);
}

所以我的确切观点是,在这种情况下,我应该使用方法注入(inject)还是 new() 运算符。 请提供您的观点。

最佳答案

您可以使用任何一种方式,因为最终客户端代码负责处理原型(prototype) bean 的生命周期而不是 spring 容器。

根据 Spring 文档,

In some respects, you can think of the Spring containers role when talking about a prototype-scoped bean as somewhat of a replacement for the Java 'new' operator. All lifecycle aspects past that point have to be handled by the client.

Spring does not manage the complete lifecycle of a prototype bean: the container instantiates, configures, decorates and otherwise assembles a prototype object, hands it to the client and then has no further knowledge of that prototype instance. It is the responsibility of the client code to clean up prototype scoped objects and release any expensive resources that the prototype bean(s) are holding onto.

关于java - 什么是最佳实践 : Use prototype bean instead of new () operator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54016936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com