Container lifecycle

Initialization

  • spring beans are created
  • dependency injection

Usage

  • beans are available

Destruction

  • beans released for GC

Initialization

Spring framework

a) Load and process bean definitions

Metadata is collected from the source, XML, Java annotations and the bean definitions are added to the BeanFactory.

The BeanFactoryPostProcessor is invoked and it can change the definition of any bean.

BeanFactoryPostProcessor is an extension point and it’s used to apply transformations to bean definitions before objects are created. It’s used to read properties, configure custom scopes, etc.

b) Perform Bean creation

Beans created with dependencies injected.

Post process phase, init methods are called, creates proxies.

Bean is ready to use.

Customization

BeanPostProcessor Interface implemented to customize bean initialization.

BeanFactoryPostProcessor operates on bean configuration metadata, it reads the configuration metadata and can change it before the container instantiates the beans.

This interfaces can be extended to provide further customization.

public class CustomBeanFactory implements BeanFactoryPostProcessor {

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        for (String beanName : beanFactory.getBeanDefinitionNames()) {

            BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);

            // Manipulate the beanDefiniton or whatever you need to do

        }
    }
}

Shutdown

 In a non-web application environment (for example, in a rich client desktop environment) shutdown hook should be registered in the JVM in order to ensure a graceful shutdown and calling the relevant destroy methods in singleton beans so that all resources are released.

public final class Boot {

	public static void main(final String[] args) throws Exception {
		ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");

		// add a shutdown hook for the above context...
		ctx.registerShutdownHook();

		// app runs here...

		// main method exits, hook is called prior to the app shutting down...
	}
}

Proxies

References

https://stackoverflow.com/questions/30455536/beanfactorypostprocessor-and-beanpostprocessor-in-lifecycle-events