We will use the same Ch02_Bean_Life_Cycle project that we developed in Case1.
Follow these steps:
- Add a Demo_DisposableBean class in the com.ch02.beans package, which implements a DisposableBean interface, as shown in the following piece of code:
public class Demo_DisposableBean implements DisposableBean { private String message; private String name; public Demo_DisposableBean() { // TODO Auto-generated constructor stub System.out.println("constructor gets called for initializing data members in Disposable Bean"); message="welcome!!!"; name="no name"; } @Override public String toString() { // TODO Auto-generated method stub return message+" "+name; } }
- Override the destroy() method for memory release, as follows:
@Override public void destroy() throws Exception { // TODO Auto-generated method stub System.out.println("destroy from disposable bean get called"); name=null; }
- Add one more bean to the beans_lifecycle.xml file, as shown in the following lines of code:
<bean id="obj_Disposable" class="com.ch02.beans.Demo_DisposableBean"/>
You will observe that we don't have to override any destroy-method attribute here as we did in Case 1. The destroy() method will get a callback once the container containing the bean gets shut down.
- Create a Test_DisposableBean class with the following code:
public static void main(String[] args) { // TODO Auto-generated method stub ApplicationContext context=new ClassPathXmlApplicationContext("beans_lifecycle.xml"); Demo_DisposableBean obj= (Demo_DisposableBean)context.getBean("obj_Disposable"); System.out.println(obj); ((AbstractApplicationContext)context).registerShutdownHook(); }
- Upon execution of the main method, we will get the output as shown in the following screenshot:
The underlined line is from the destroy() method from the Disposable demo, but there is a custom destroy() method for the Demo_Custom_Init class as well.
Until now, we discussed how to configure a bean, and how to perform it's the initialization. Initialization is one of the steps which help the developers to set the values of the dependencies. None of us love to live a boring life. We need adventure, we want to explore our surroundings, the nature in which we live. Our bean is also similar to us. The bean wants to explore and know about the environment where it spends its life.