春豆的生命周期是什么? [英] What is the lifecycle of spring bean?

查看:140
本文介绍了春豆的生命周期是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am confused about the lifecycle of Spring.

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

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

Whether the above snippet of codes creates the object or not?

如果上述答案为真。

a)然后,对于范围为singleton的bean,获取在上面的代码片段中创建的对象。我是对还是错?

a) Then, for the bean where scope is "singleton" get the object which was created during the above snippet of code. Am i right or wrong?

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

b) For the case where scope is "prototype", whether the created object was unused. 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?

如果答案为假,

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

How the spring framework validates whether the bean definition is correct or not.

来自Henry的回答

From the answer of Henry

通常,在上下文启动时会创建单例bean。这可以使用lazy-init或default-lazy-init属性进行更改。

仅创建原型bean需要时。

仅在语法上,实例化bean时可能仍然存在错误,例如,如果需要属性未提供。

推荐答案

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

BeanFactory does not pre-instantiate singletons on startup like ApplicationContext does. So even if your bean is non-lazy and singleton, it won't be created.

prototype beans is按需创建,每次你要求原型bean时,你都会获得一个新实例。但是一旦在自动装配期间使用了这样的bean,将永远使用相同的实例。

prototype beans are created on demand, every time you ask for a prototype bean you'll get a new instance. But once such bean was used during autowiring, the same instance will be used forever.

使用 ApplicationContext 所有单例都是仅按需创建热切的原型bean。

With ApplicationContext all singletons are created eagerly and prototype beans only on demand.

  • BeanFactory vs ApplicationContext

这篇关于春豆的生命周期是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆