11

我对 Spring 的生命周期感到困惑。

XmlBeanFactory beanFactory 
= new XmlBeanFactory(new ClassPathResource("SpringHelloWorld.xml"));

上面的代码片段是否创建了对象?

如果上面的答案是真的。

a) 然后,对于作用域为“单例”的 bean,获取在上述代码片段中创建的对象。我是对还是错?

b) 对于范围为“原型”的情况,创建的对象是否未被使用。因为,容器总是返回新对象。

XmlBeanFactory beanFactory 
= new XmlBeanFactory(new ClassPathResource("SpringHelloWorld.xml"));

上面的代码片段是否创建了对象?

如果答案是假的,

spring 框架如何验证 bean 定义是否正确。

From the answer of Henry

Usually, singleton beans are created when the context starts. This can be changed with the lazy-init or default-lazy-init attributes.

Prototype beans are only created when needed.

Only syntactically, there might still be errors when the bean is instantiated, for example if a required property is not provided.

4

2 回答 2

8

BeanFactory不会像ApplicationContext这样在启动时预先实例化单例。因此,即使您的 bean 是非惰性和单例的,它也不会被创建。

prototypebean 是按需创建的,每次您请求原型 bean 时,您都会得到一个新实例。但是一旦在自动装配过程中使用了这样的 bean,同一个实例将永远被使用。

ApplicationContext所有的单例都是急切地创建的,原型 bean 仅在需要时才创建。

也可以看看

于 2012-12-21T11:00:01.757 回答
1

通常,单例 bean 是在上下文启动时创建的。这可以用lazy-initordefault-lazy-init属性来改变。

原型 bean 仅在需要时创建。

于 2012-12-21T10:58:12.360 回答