Monday, September 29, 2014

Preloading and Lazy loading Beans

Employee emp = (Employee) factory.getBean("employeeBean"); // 2
Even though "beans.xml" configuration file is loaded with BeanFactory container in line number 1, none of the beans will be instantiated. Instantiation takes place only at line number 2, where bean called "employeeBean" is requested from container. Since the class is instantiated at getBean() method call, time spend to return this method will vary depending on the instantiated object.


ApplicationContext context =
            new ClassPathXmlApplicationContext("beans.xml"); // 1
Employee emp = (Employee) context.getBean("employeeBean"); // 2
As all singleton beans are instantiated by container at line number 1, this line will take some considerable time to complete. However line number 2 will return the bean instance immediately since instances are already available inside the container.


destroy-method="close">

The init-methodattribute specifies a
method that is to be called on the beanimmediately upon instantiation. Similarly,
destroy-method specifies a method that is called just before a bean is removed from
the container.In our case



When some Web Application Shut downs Spring's web-based ApplicationContext handles shutting down gracefully but for a non web application if you want the container to shutdown gracefully and call the relevant destroy callbacks on your singleton beans, you will need to register a shutdown hook with the JVM.

So for registering a shutdown hook that enables the graceful shutdown for the relevant Spring IoC container, we simply need to call the registerShutdownHook () method that is declared on the AbstractApplicationContext class.

public final class Test {

public static void main(final String[] args) throws Exception {

AbstractApplicationContext ctx= new ClassPathXmlApplicationContext(new String []{"test.xml"});
ctx.registerShutdownHook();
// app runs here...
// main method exits, hook is called prior to the app shutting down...
}
}

when container is shut down it is destroyed .But in our case the bean is never destroyed and application context is also not shutdown unless tomcat is restarted .context.close()destroyed.and at that time the destroy method that is defined in bean definition file is called for example in our case it is close which is called
'

destroy-methodspecifies a method that is called just before a bean is removed from
the container.

No comments:

Post a Comment