Spring BeanFactoryPostProcessor Example
October 30, 2021
On this page we will learn Spring BeanFactoryPostProcessor
example. The BeanFactoryPostProcessor
interface works as a factory hook that allows for custom modification of an application context's bean definitions, adapting the bean property values of the context's underlying bean factory.
The
BeanFactoryPostProcessor
interface has following method.
void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
The
BeanFactoryPostProcessor
is a functional interface and can be used as assignment target for lambda expression or method reference.
Implement BeanFactoryPostProcessor
BeanFactoryPostProcessorTest.javapackage com.concretepage; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; public class BeanFactoryPostProcessorTest implements BeanFactoryPostProcessor { @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { System.out.println("Inside postProcessBeanFactory method."); } }
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd "> <bean class="com.concretepage.BeanFactoryPostProcessorTest" /> <bean id= "testBean" class="com.concretepage.TestBean" /> </beans>
package com.concretepage; public class TestBean { public TestBean(){ System.out.println("Object of TestBean is created."); } }
package com.concretepage; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringTest { public static void main(String[] args) { AbstractApplicationContext context = new ClassPathXmlApplicationContext("app-conf.xml"); context.registerShutdownHook(); } }
Inside postProcessBeanFactory method. Object of TestBean is created.