【问题标题】:What is the lifecycle of spring bean?spring bean 的生命周期是什么?
【发布时间】:2012-12-08 22:48:00
【问题描述】:

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

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

上面的sn-p代码是否创建了对象?

如果上面的答案是真的。

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

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

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

上面的sn-p代码是否创建了对象?

如果答案是假的,

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.

【问题讨论】:

    标签: java spring lifecycle


    【解决方案1】:

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

    原型 bean 仅在需要时创建。

    【讨论】:

    • 对于原型,在启动时spring是否验证bean定义下定义的属性?
    • 仅在语法上,实例化 bean 时可能仍然存在错误,例如,如果未提供必需的属性。
    【解决方案2】:

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

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

    使用ApplicationContext,所有单例都被急切地创建,原型bean 仅在需要时。

    另见

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多