Wednesday, 22 January 2014

Spring ApplicationContext Bean Initialisation

Important Spring knowledge, but often poorly understood.  Beans are created and initialised by the ApplicationContext as follows (following sequence done for each bean):
  1. bean constructor called
  2. bean setters called
  3. postProcessBeforeInitialization() method called for each BeanPostProcessor
  4. bean @PostConstruct method(s) called
  5. if bean implements InitializingBean, afterPropertiesSet() method called
  6. bean init-method called if configured
  7. postProcessAfterInitialization() method called for each BeanPostProcessor
[ BeanFactoryPostProcessor is something different, it is called before any bean initialisation, and can used to alter the bean metadata]

Let's write some code to illustrate this:

TestBean.java

package com.example;

import org.springframework.beans.factory.InitializingBean;
import javax.annotation.PostConstruct;

public class TestBean implements InitializingBean {

    private String text;

    public TestBean() {
        System.out.println("constructor");
    }

    public void setText(String text) {
        System.out.println("setter");
        this.text = text;
    }

    @PostConstruct
    public void postConstructInitialisation() throws Exception {
        System.out.println("postConstructInitialisation");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("afterPropertiesSet");
    }

    public void init() {
        System.out.println("init");
    }

}


TestBeanPostProcessor.java

package com.example;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

public class TestBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("TestBeanPostProcessor postProcessBeforeInitialization");
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println("TestBeanPostProcessor postProcessAfterInitialization");
        return bean;
    }
}


application-context.xml (snippet)
    
    <bean class="com.example.TestBeanPostProcessor">

    <bean class="com.example.TestBean" init-method="init">
        <property name="text" value="Hello"/>
    </bean>


output:

constructor
setter
TestBeanPostProcessor postProcessBeforeInitialization
postConstructInitialisation
afterPropertiesSet
init
TestBeanPostProcessor postProcessAfterInitialization

No comments:

Post a Comment