Spring BeanFactoryAware Interface
0 CommentsLast Updated on June 15, 2019 by Simanta
Core to the Spring Framework is a concept of bean factories. Spring bean factories follow the concepts of the GoF Factory Design Pattern to provide the requestor fully configured objects.
Under the covers when the Spring Framework is performing dependency injection on your beans, Spring itself will use bean factories to obtain a fully configured bean to inject into your class.
Normally, it is recommended that you allow Spring to manage dependent objects itself through the use of dependency injection. If you find the need to access the Spring bean factory through the use of the BeanFactoryAware
interface, I would suspect you’re doing something incorrect.  Generally speaking, you’re better off allowing Spring to inject dependent beans into your objects. This is even mentioned in the Spring javadoc for the BeanFactoryAware
Interface.
Note that most beans will choose to receive references to collaborating beans via corresponding bean properties or constructor arguments (Dependency Injection).
While you can get beans directly from the Spring bean factory, in doing so, you’re creating a dependency on the Spring bean factory in your class. You’re likely better off allowing Spring to Autowire the dependent object into your class for you.
Implementing the BeanFactoryAware Interface
Should you need to obtain a reference to the bean factory, implementing the BeanFactoryAware
Interface is simple enough. Here is an example of a class which implements the BeanFactoryAware
Interface.
FactoryAwareBean.java
package guru.springframework.lifecyclebeans; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.BeanFactoryAware; import org.springframework.stereotype.Component; @Component public class FactoryAwareBean implements BeanFactoryAware { @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { System.out.println("I got the factory!"); } }
During the initialization of the Spring context, Spring will inject an instance of the bean factory used to create this bean into the class. In this example, I’m not interacting with the bean factory. I’m just writing a short message to the console to prove the method was called.
Free Introduction to Spring Tutorial
Demonstration of Using the BeanFactoryAware Interface
I have a short YouTube video demonstrating the usage of the BeanFactoryAware
Interface.