We read about the bean's life cycle; why don't we try to examine the life cycle?
Modify the HelloWorld
class and implement the following Spring Framework interfaces:
ApplicationContextAware
: This will ask you to implement thesetApplicationContext
methodBeanNameAware
: This will tell you to implement thesetBeanName
methodInitializingBean
: This will force you to implement theafterPropertiesSet()
methodBeanFactoryAware
: This will request you to implement thesetBeanFactory
methodBeanPostProcessor
: This needs you to implement thepostProcessBeforeInitialization
andpostProcessAfterInitialization
methodsDisposableBean
: This needs to implement thedestroy()
method
Add the System.out.println
statement in all the implemented methods. Now, add the following two methods:
public void myInit() { System.out.println("custom myInit is called "); } public void myDestroy() { System.out.println("custom myDestroy is called "); }
Modify the bean definition to call the init-method
and destroy-method
methods. The following is the modified bean definition:
<bean id="helloWorld" class="com.packt.lifecycle.HelloWorld" init-method="myInit" destroy-method="myDestroy"> <property name="message" value="Welcome to the Spring world"> </property> </bean>
Now, modify HelloWorldExample
to destroy the application context by registering to shutdown hook. The following is the modified code:
AbstractApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); HelloWorld world = (HelloWorld) context.getBean("helloWorld"); System.out.println(world.getMessage()); context.registerShutdownHook();
When we run the application, the following output is displayed:
Note that the setBeanName
method is invoked first, then the setBeanFactory
, setApplicationContext
, and afterProperiesSet
methods are called, and then the custom init
method is invoked. During destruction, the destroy
method is called first and then the custom destroy-method
is invoked.