BeanFactoryPostProcessor
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
}
}
}
BeanPostProcessor
The BeanPostProcessor interface can be itself customized logic to default steps, when Spring container finishes instantiating, configuring, and initializing a bean, several implementations of BeanPostProcessor can be called.
public class InstantiationTracingBeanPostProcessor implements BeanPostProcessor {
// simply return the instantiated bean as-is
public Object postProcessBeforeInitialization(Object bean, String beanName) {
return bean; // we could potentially return any object reference here...
}
public Object postProcessAfterInitialization(Object bean, String beanName) {
System.out.println("Bean '" + beanName + "' created : " + bean.toString());
return bean;
}
}
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...
}
}