Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the lifecycle of spring bean?

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.

like image 834
Shashi Avatar asked Dec 21 '12 10:12

Shashi


2 Answers

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
like image 129
Tomasz Nurkiewicz Avatar answered Sep 28 '22 05:09

Tomasz Nurkiewicz


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.

like image 30
Henry Avatar answered Sep 28 '22 04:09

Henry