
Lazy Loading
A bean is loaded only when an instance of that Java class is requested by any other method or a class. org.springframework.beans.factory.BeanFactory (and subclasses) container loads beans lazily. Following code snippet demonstrate lazy loading, concentrate on how "beans.xml" spring configuration file is loaded by BeanFactory container class.
BeanFactory factory =
new XmlBeanFactory(
new InputStreamResource(
new FileInputStream("beans.xml")));// 1
Employee emp = (Employee) factory.getBean("employeeBean");// 2
Pre-loading
All beans are instantiated as soon as the spring configuration is loaded by a container. org.springframework.context.ApplicationContext container follows pre-loading methodology.
ApplicationContext context =
new ClassPathXmlApplicationContext("beans.xml"); 1
Employee emp = (Employee) context.getBean("employeeBean"); // 2
Thanks for describing the difference in using two factories
ReplyDeleteShort, but explains all.
ReplyDeleteThanks
Michel
Simple and Clear explanation
ReplyDeleteLazy instantiation should not be done using FileInputStream. With spring 2, using it the way you described, validation mode of the xml would not be automatically determined, and you would get BeanDefinitionStoreException. That approach should be avoided. Instead you should specify your bean to be lazy initialized by adding "lazy-init="true" to your bean declaration.
ReplyDeleteErni
Nice explanation of the difference. Thank you.
ReplyDeleteExactly what I was looking for. Thanks a lot!
ReplyDeleteSimple and easily understandable explanation. keep it up.
ReplyDeleteThanks For describing Lazy and Eager loading in Spring.
ReplyDeleteCould you explain Singleton behavior for BeanFactor and ApplicationContext
Thanks for the nice explanation.
ReplyDeleteif you want to get same eager behaviour with BeanFactory then You have to invoke the method 'preinstantiateSingletons()' on your XmlBeanFactory to get the same behaviour as an application context.
ReplyDelete