3

Spring 定义了 bean 定义的不同范围,一个是原型范围,它在每次查找时都会给出一个新实例。

我对此有两个疑问..

  1. 在幕后,spring 如何创建一个新实例?
  2. 我听说,它使用 clone() 方法来创建一个新实例,如果是,那么为什么以及如果它使用克隆来提供一个新实例,那么克隆对象的状态会发生什么,因为克隆也会复制状态?
4

2 回答 2

6
  1. Like any other bean: using the constructor annotated with @Autowired, or the default one if there isn't any (or a factory method if one is defined).

  2. What you heard is wrong. Most objects are not cloneable, so it would only get an exception by doing that. And it would make no sense since

    • it wouldn't be able to create the first instance
    • all the instances would be the same as the first one, which is clearly not what is wanted.
于 2012-09-30T20:07:47.147 回答
0

Spring 使用反射机制来创建新实例。Spring,首先查找单例映射,如果没有找到实例,使用bean定义创建新实例,它将应用定义的生命周期。所以你听到的是错误的。

于 2012-10-02T09:25:59.980 回答