What is Spring Container callbacks or Spring lifecycle methods

In this article, learn about Spring Container callbacks or Spring lifecycle methods. We will learn about life cycle stages, initialization and destroy call back methods. We will learn to control the bean life cycle events using XML configuration as well as annotation configuration.
Spring Container callbacks or Lifecycle methods are as follows:

  1. Initialize callbacks
  2. Disposable callbacks
  3. Knowing who you are and where you are
  4. Extending spring container functionality

Initialization callbacks:

  • You can initialize the resources required for your bean by using the wiring process.
  • Sometimes, you may get the required to initialize the resources required for your bean explicitly or you may want to verify the resources injected by the spring container.
  • In this case, you to write the resources initialization code or verification code inside the initialization callbacks

Spring supports 3 ways for initialization.

  1. Write your own initialization method and mark that with @Postconstruct annotation.
  2. Implement initialization bean interface and override the following method. Public void after properties set()

3. write your own initialization method and specify the method name in bean definition ( in XML)

Example:

class Hello implements initializing the bean
{

@PostConstruct
public void init()
{
// initialization code
}

public void afterPropertiesSet() {
  //initialization code
}

public void myInit()
{
//initialization code
}
}

In XML

<bean id=”hello” class=”com.xadmin.Hello” init-method=”nyInit”/>

Disposable callbacks:

  1. You may get the requirement to clean up the resource which is initialized at the time of creating the bean instance.
  2. You write the resources clean up code inside the Disposable callbacks.

Spring supports 3 ways for cleanup the resources.

  1. Write your own cleanup method and mark that with @preDestroy annotation.
  2. Implement disposable bean interface and override the following method
    public void destroy()
  3. Write your own cleanup method and specify the method name in a bean definition

Example:

class Hello implements DisposableBean
{
@PreDestroy
public void cleanup()
{
//cleanup code
}
public void destroy()
{
//cleanup code
public void myCleanup(){
//cleanup code
}
}

In XML

<bean name=”hello” class=”com.xadmin.Hello” destroy-method=”myCleanup”/>

Knowing who you are and where you are:

  • Sometimes bean wants to know that its name is and where it is running.
  • For this, you can use the following 3 aware interfaces.
    • Bean Name Aware
    • Bean Factory Aware
    • Application Context-Aware
  • When bean wants to know its name then bean class has to implement a bean name aware interface and has to override the following method.
    Public void set bean factory(Bean Factory factory)
  • when bean wants to get the application context reference then bean class has to implement Application Context-Aware interface and has to override the following method.

Public void set Application Cation Context(Application Context ctxs)

Note:

  • Bean Factory and Application context objects can be injected into the bean in two ways
    UsingAware Interfaces.
    Using @Autowired

Extending container functionality:

  • You can extend the spring container functionality using a bean post processor interface.

Steps:

  • Write your own Custom class by implementing a bean post processor interface.
  • Override the following 2 methodsPublic object post process BeforeInitialization(Object bean, String bn)
    public object post process AfterInitialization(Object bean, String bn)
  • Register your Bean Post Processor with the spring container.

Spring Container

  • There are two types of containers provided.
    • Bean Factory Container
    • Application Context Container
  • You can create the Bean Factory Container as follows:
    • Resource res=new Class-Path Resource(“xadmin.xml”);
    • Resource res=new File System Resource(“path of xadmin.xml”);
    • Bean Factory factory = new xmlBeanFactory(res);

Life of bean in the Bean Factory container:

  1. Container loads the bean class into memory
  2. The container creates the Bean instance by using corresponding constructor(constructor injection)
  3. Bean dependencies will be injected with the following ways:
  4. When bean class is implementing bean name aware interface then set bean Name() method will be called by the container.
  5. When bean class is implementing bean Factory aware interface then set bean factory (0 methods will be called by the container.
  6. When bean class is implementing initializing bean interface then after properties set(o method will be called by the container.
  7. When bean definition container inits method attributes then that specified method will be called.
  8. Fully initialized bean instance will be ready to use in the bean factory container.
    1. At container shutdown time, it will destroy all the bean instance.
    2. When a container is destroying one bean instance, it will do the following tasks.
  • When bean class is implementing DisposalBean interface the destroy() method will be called by the container.
  • When bean definition contains destroy- method attribute then that specified method will be called.

Application Context Container

  • Application context interface has three concrete implementations.
    • Classpath XML application context
    • File system XML application context
    • XML web application context
  • You can create the application context container as follows:
    • Application context ctx=new classPathXmlApplicationContext(“xadmin.xml”);
    • Application context ctx=new FilesystemxmlApplicationcontext(“path of the xadmin.xml file);

Life of Bean in the Application Context container

  1. Container loads the bean class into memory.
  2. The container creates the bean instance by using corresponding constructor(constructor injection)
  3. Bean dependencies will be injected with the following ways:
    1. Annotation-based auto-wiring(Filed Injection)
    2. XML based explicit wiring(setter injection)
    3. XML based auto-wiring (setter injection)
  4. When bean class is implementing bean name aware interface then set bean name() method will be called by the container.
  5. When bean class is implementing bean Factory Aware interface then set bean Factory() method will be called by the container.
  6. When bean class is implementing the Application Context-Aware interface then set Application Context() method will be called by the container.
  7. When the bean post processor is registered then post process BeforeInitialization() method will be called by the container.
  8. When any method is found with @Post construct annotation then that method will be called.
  9. When be class is implementing initializing bean interface then after properties set() method will be called by the container.
  10. When bean definition contains the init method attribute then that specified method will be called.
  11. When bean Post-processor is registered then post process After Initialization() method will be called by the container.
  12. Fully initialized bean instance will be ready to use in the Application context container.
    1. When any method is found with @PreDestroy annotation then that method will be called
    2. When bean class is implementing Disposable bean interface then destroy() method will be called by the container.
    3. When bean definition contains a destroy method attribute then that specified method will be called.

Bean Factory

Application Factory

Bean factory is an interface which has one concrete subclass class XMLBeanFactory The application context is an interface which has 3 concrete subclasses called:

  • ClassPathxmlApplicationContext
  • FileSystemXmlApplicationContext
  • XmlWebApplicationContext
Bean configured with Bean Factory container will be loaded lazily by default Beans configured with application context

the container will be loaded aggressively by default

Bean factory container doesn’t support annotations. Application context container supports annotation.
Bean factory container doesn’t support Event publishing Application context container supports Event publishing.
Bean factory container doesn’t provide the way to resolve message bundles Application context container provides to way to resolve message bundles.
Bean factory container doesn’t support Bean post processor Application context container supports bean post processor

Similarities between Bean factory container and Application Context container.
Both containers will do the following common tasks:

  1. Loads bean classes.
  2. Create the bean dependencies.
  3. Injects the bean instances as long as the container is running
  4. Maintains the bean instances as long as the container is running.
  5. Destroys the Bean instances at shut down time.

Bean definition

<bean id=””
Name=” ”
Class=” ”
Lazy-init=” ”
scope=” ”
autowire=” ”
init-method=””
destroy-method=” ”
abstract=” ”
parent=” ”

Example: File required
xadmin.java
A.java
B.java
xadmin.xml
MyBeanPostPreocessor.java
Hello.java

Xadmin.java

package com.xadmin.spring;
import org.springframework.context.support.*;

public class Xadmin {
public static void main (string[] args) 
{
AbstractApplicationContext ctx= new classPathApplicationContext(“xadmin.xml”);

or
*/
AbstractApplicationContext ctx= new FileSystemXmlApplicationContext(“path of the xadmin.xml”);
  
System.out.println(“spring container is Ready...”);
System.out.println(“..............”);
Hello hello(Hello)ctx.getBean(“Hello”);
Hello.show();
System.out.println(“.....................”);
System.out.println(“spring container going to shutdown...”);
ctx.register.ShutdownHook();
}
}

A.java

package com.xadmin.spring;
import org.springframework.context.support.*;

public class A {
private int a;
private string msg;
static {
System.out.println(“A-S-B”);
}
public A()
{
System.out.println(“A()”);
}
public void setA(int a)
this.a=a;
}
public void setMsg(“string msg){
This.msg=msg;
}
@PostConstruct
public void init()
{
System.out.println(“A-init()”);
}
}

B.java

package com.xadmin.spring;
import org.springframwork,context.support.*;

public class B 
{
private int b;
private string str;
static 
{
System.out.println(“B-S-B”);
}
public B() {
System.out.println(“B-()”);
}
public B(int b, string str);
{
System.out.println(“B-(int, string)”);
this.b=b;
this.str=str;
}
@postConstruct
public void init()
{
System.out.println(“B-init()”);
}
public string toString()
{
return “”+b+”\t”+str;
}

MyBeanPostProcessor.java

package com.xadmin.spring;
import org.spring.framework.beans.Exception;

public class MyBeanPostProcessor implements BeanPostProcessor {
public object postProcessBeforeInitialization (Object string bname) throws beanException {
System.out.println(“Post process beforeInitialization:”+bname);
return obj;
}
Public object postProcessAfterInitialization(Object obj, string bname) throws BeanException
{
System.out.println(“post process AfterInitialization:”+ bean);
return obj;
}
}

Hello.java

package com.xadmin.spring;
import javax.annotation.*;
import org.spring.framework.beans.*;
import org.spring.framework.beans.factory.*;
import org.spring.framework.beans.factory.annotation.autowired;
import org.springframework.context.*;

@postContruct
public vopid init();
System.out.println(“hello-init()”);
if(str==null)
{
str==”Hai Viewers”;
}
}
public void afterPropertiesSet() throws Exception {
System.out.println(“Hello after properties Set()”);
Msg=”welcome to Xadmin”;
if(str==null)
{
Str=”hai Guys”;
}
}

public class hello Implements Initializingbean, Disposable bean, beanNameAware, Bean FactoryAware, ApplicationContextAware 
{
int x;
string str;
string msg;
string bname;

@Autowired
A aobj;
B bobj;

Application Context ctx1;
BeanFactory factory1;

@Autowired
Application Context ctx2;
@Autowired 
beanFactory factory2;
static{
System.out.println(“Hello-S-B”);
}
public hello(int x)
{
System.out.println(“Hello-(int-x);
this.x=x;
}
public void setBobj(B bobj)
{
System.out.println(“hello-setBobj()”);
this.obj=bobj;
}
@postContruct
public void init1()
{package com.xadmin.spring;
import javax.annotation.*;
import org.spring.framework.beans.*;
import org.spring.framework.beans.factory.*;
import org.spring.framework.beans.factory.annotation.autowired;
import org.springframework.context.*;

@postContruct
public vopid init();
System.out.println(“hello-init()”);
if(str==null)
{
str==”Hai Viewers”;
}
}
public void afterPropertiesSet() throws Exception {
System.out.println(“Hello after properties Set()”);
Msg=”welcome to Xadmin”;
if(str==null)
{
Str=”hai Guys”;
}
}

public class hello Implements Initializingbean, Disposable bean, beanNameAware, Bean FactoryAware, ApplicationContextAware 
{
int x;
string str;
string msg;
string bname;

@Autowired
A aobj;
B bobj;

Application Context ctx1;
BeanFactory factory1;

@Autowired
Application Context ctx2;
@Autowired 
beanFactory factory2;
static{
System.out.println(“Hello-S-B”);
}
public hello(int x)
{
System.out.println(“Hello-(int-x);
this.x=x;
}
public void setBobj(B bobj)
{
System.out.println(“hello-setBobj()”);
System.out.println(“Hello-intit1()”);
Msg=”welcome to xadmin”);
if(str==null)
{
str=”Hai Guys”;
}
}
public void myInit()
{
System.out.println(“Hello-myInit/()”);
msg=”welcome to xadmin”;
if(str==null)
{
str=”hai Guys”;
}
}

public void setBeanName(string bname)
{
System.out.println(“Hello-setBean Name()”);
this.bname;
}
public void setBeanFactory(beanFactory)
{
System.out.println(“Hello setBeanFactory()”);
this.factory1=factory1;
}
public void setApplicationContext(Application Context ctx);
{
System.out.println(“hello-set-ApplicationContext()”);
this.ctx1=ctx1;
}
@preDestroy
public void cleanup()
{
System.out.println(“Hello-cleanup()”);
}
public void destroy() throws Exception
{
System.out.println(“Hello-destroy()”);
}
public void myCleanup()
{
System.out.println(“Hello-myCleanup()”);
}

public void show()
{
System.out.println(“Hello-show()”);
System.out.println(x);
System.out.println(str);
System.out.println(msg);
System.out.println(“bean Name is+bname);
System.out.println(factory);
System.out.println(ctx1);
System.out.println(factory2);
System.out.println(ctx2);
System.out.println(ctx1==ctx2);
System.out.println(factory1==factory2);
}
}

Xadmin.xml

<beans...>
<context:annotation-config/>
<bean id=”AO” class=”com.xadmin.spring.A”>
<property name=”a” value=”99”/>
<property name=”msg” value=”AAA”/>
</bean>

<bean id=”bobj” class=”com.xadmin.spring.A”>
<constructor-arg value=”88”/>
<constructor-arg value=”BBB”/>
</bean>

<bean id=”Hello” class=”com.xadmin.spring.Hello” init-method=”myinit” Destroy-method=”mycleanup” autowire=”byname”>
<constructor-arg value=”99”/>
<property name=”str” value=”Hello Guys”/>
</bean>
<bean class=com.xadmin.spring.MyBeanPostProcessor”/>
<beans>

So this is all about spring bean life cycle methods inside Spring container. Remember given types of life cycle events, it is a commonly asked in spring interview questions.
I hope that this article was helpful to you and added some more knowledge about the spring container. Please, feel free to drop a comment in the comment box below if you find any doubt regarding the topic or you want to share more information about the topic.
Happy Learning !!

 

Leave a Reply

Your email address will not be published. Required fields are marked *