Advanced Java (2160707)

BE | Semester-4   Winter-2018 | 20-11-2018

Q5) (b)

Briefly explain spring bean life cycle.

Spring Bean

  • The life cycle of a spring bean is easy to understand. When a bean is instantiated, it may be required to perform some initialization to get it into a usable state. Similarly, when the bean is no longer required and is removed from the container, some cleanup may be required.
  • Though, there is lists of the activities that take place behind the scenes between the time of bean Instantiation and its destruction, but this chapter will discuss only two important bean lifecycle callback methods which are required at the time of bean initialization and its destruction
  • To define setup and teardown for a bean, we simply declare the with init-method and/or destroy-method parameters. The init-method attribute specifies a method that is to be called on thebean immediately upon instantiation. Similarly, destroy-method specifies a method that is called just before a bean is removed from the container

HelloWorld.java

public class HelloWorld
{
    private String message;
    public void setMessage(String message)
    {
        this.message = message;
    }
    public void getMessage()
    {
        System.out.println("Your Message : " + message);
    }
    public void init()
    {
        System.out.println("Bean is going through init.");
    }
    public void destroy()
    {
        System.out.println("Bean will destroy now.");
    }
}