Spring BeanFactoryAware Interface Example

By Arvind Rai, October 29, 2021
On this page we will learn Spring BeanFactoryAware interface. The BeanFactoryAware interface is implemented by beans that wish to be aware of their BeanFactory.
The BeanFactoryAware interface has a method.
void setBeanFactory(BeanFactory beanFactory) throws BeansException 
This method supplies the owning factory to a bean instance. This method is invoked after the population of normal bean properties but before an initialization call back.

Implement BeanFactoryAware Interface

A.java
package com.concretepage;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
public class A implements BeanFactoryAware {
	@Override
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
	    System.out.println("setBeanFactory:"+beanFactory);
	}
	public A(){
		System.out.println("Bean A is Initialized.");
	}
} 
app-conf.xml
<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 id="testA" class="com.concretepage.A"/>
</beans>  
SpringTest.java
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();
	}
} 
Output
Bean A is Initialized.
setBeanFactory:org.springframework.beans.factory.support.DefaultListableBeanFactory@16df1832: defining beans [testA]; root of factory hierarchy 

Reference

Interface BeanFactoryAware
POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us