What is the lifecycle of spring bean?

▼魔方 西西 提交于 2019-12-22 03:59:11

问题


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?

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. Am i right or wrong?

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?

If the answer is false,

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

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.


回答1:


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 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.

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

See also

  • BeanFactory vs ApplicationContext



回答2:


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.



来源:https://stackoverflow.com/questions/13988720/what-is-the-lifecycle-of-spring-bean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!