Book Image

Mockito for Spring

By : Sujoy Acharya
Book Image

Mockito for Spring

By: Sujoy Acharya

Overview of this book

Table of Contents (12 chapters)
Mockito for Spring
About the Author
About the Reviewers

Examining life cycle messages

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 the setApplicationContext method

  • BeanNameAware: This will tell you to implement the setBeanName method

  • InitializingBean: This will force you to implement the afterPropertiesSet() method

  • BeanFactoryAware: This will request you to implement the setBeanFactory method

  • BeanPostProcessor: This needs you to implement the postProcessBeforeInitialization and postProcessAfterInitialization methods

  • DisposableBean: This needs to implement the destroy() 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">

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");

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.