简体   繁体   English

春豆的生命周期是什么?

[英]What is the lifecycle of spring bean?

I am confused about the lifecycle of Spring. 我对Spring的生命周期感到困惑。

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

Whether the above snippet of codes creates the object or not? 上面的代码片段是否创建了对象?

If the above answer is true. 如果上述答案是真的。

a) Then, for the bean where scope is "singleton" get the object which was created during the above snippet of code. a)然后,对于范围为“singleton”的bean,获取在上面的代码片段中创建的对象。 Am i right or wrong? 我是对还是错?

b) For the case where scope is "prototype", whether the created object was unused. b)对于范围是“原型”的情况,创建的对象是否未使用。 Because, the container always return new object. 因为,容器总是返回新对象。

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

Whether the above snippet of codes creates the object or not? 上面的代码片段是否创建了对象?

If the answer is false, 如果答案是假的,

How the spring framework validates whether the bean definition is correct or not. 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.

BeanFactory does not pre-instantiate singletons on startup like ApplicationContext does. BeanFactory不像ApplicationContext那样在启动时预先实例化单例。 So even if your bean is non-lazy and singleton, it won't be created. 所以,即使你的bean是非懒惰和单身,它也不会被创建。

prototype beans are created on demand, every time you ask for a prototype bean you'll get a new instance. prototype bean是按需创建的,每次你要求原型bean时你都会得到一个新实例。 But once such bean was used during autowiring, the same instance will be used forever. 但是一旦在自动装配期间使用了这样的bean,将永远使用相同的实例。

With ApplicationContext all singletons are created eagerly and prototype beans only on demand. 使用ApplicationContext所有单例都是热切创建的,并且只在需要时创建bean。

See also 也可以看看

Usually, singleton beans are created when the context starts. 通常,在上下文启动时会创建单例bean。 This can be changed with the lazy-init or default-lazy-init attributes. 这可以使用lazy-initdefault-lazy-init属性进行更改。

Prototype beans are only created when needed. 原型bean仅在需要时创建。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM