Understanding BeanFactory vs FactoryBean in Spring: Key Differences and Usage
This article explains the distinct roles of Spring's BeanFactory and FactoryBean, compares their functionalities, outlines how to retrieve beans and FactoryBeans, and provides practical code examples and usage scenarios for creating complex objects within the Spring IoC container.
Interview Answer: BeanFactory and FactoryBean
BeanFactoryand FactoryBean are two different concepts in the Spring framework; BeanFactory is a factory, while FactoryBean is a bean managed by the factory . BeanFactory is the core interface of the Spring IoC container, responsible for managing, assembling and distributing beans. In short, it is a bean management factory used to generate and manage various bean instances.
In contrast, FactoryBean is a special bean that is also managed by BeanFactory, but it itself is a factory bean capable of producing other bean instances. When you need complex bean creation logic or dynamic decision of bean type, you can implement the FactoryBean interface.
The main difference: BeanFactory is a container that manages beans; FactoryBean is a bean that can produce other beans.
In summary: Although their names are similar, BeanFactory and FactoryBean have completely different functions and positions. BeanFactory is the container that manages all beans in Spring, including FactoryBean. FactoryBean is a special bean that can produce other bean instances.
To obtain the object produced by a FactoryBean, use getBean("beanName").
To obtain the FactoryBean itself, use getBean("&beanName").
BeanFactory
BeanFactoryis the foundational infrastructure of the Spring framework and the core interface of the IoC container. Its main responsibilities include:
Managing the lifecycle of various beans in Spring.
Wiring dependencies between beans.
Providing bean instantiation and initialization services.
The BeanFactory interface defines basic methods for accessing the Spring IoC container:
public interface BeanFactory {
Object getBean(String name) throws BeansException;
<T> T getBean(String name, Class<T> requiredType) throws BeansException;
<T> T getBean(Class<T> requiredType) throws BeansException;
// other methods...
}When calling getBean(), BeanFactory returns a bean instance. In practice, developers often use ApplicationContext, a sub‑interface of BeanFactory that offers more features.
FactoryBean
FactoryBeanis a factory bean that can produce objects; it is an interface used when a complex object needs to be instantiated in the IoC container.
Definition of the FactoryBean interface:
public interface FactoryBean<T> {
T getObject() throws Exception;
Class<?> getObjectType();
boolean isSingleton();
}When a FactoryBean is configured in the Spring container, retrieving the bean with getBean("myFactoryBean") returns the object produced by the FactoryBean, while getBean("&myFactoryBean") returns the FactoryBean instance itself.
Example code demonstrating a custom FactoryBean that creates a complex object:
// 1. Define a complex object
public class ComplexObject {
private String property1;
private int property2;
// getters and setters omitted
@Override
public String toString() {
return "ComplexObject [property1=" + property1 + ", property2=" + property2 + "]";
}
}
// 2. Implement FactoryBean to create the complex object
public class ComplexObjectFactoryBean implements FactoryBean<ComplexObject> {
private String propertyValue;
private int intPropertyValue;
public void setPropertyValue(String propertyValue) { this.propertyValue = propertyValue; }
public void setIntPropertyValue(int intPropertyValue) { this.intPropertyValue = intPropertyValue; }
@Override
public ComplexObject getObject() throws Exception {
System.out.println("Creating ComplexObject via FactoryBean");
ComplexObject complexObject = new ComplexObject();
complexObject.setProperty1(propertyValue);
complexObject.setProperty2(intPropertyValue);
return complexObject;
}
@Override
public Class<?> getObjectType() { return ComplexObject.class; }
@Override
public boolean isSingleton() { return true; }
}
// 3. Usage example
public class FactoryBeanDemo {
public static void main(String[] args) {
// Create IoC container
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
// Get the object produced by the FactoryBean
ComplexObject complexObject = context.getBean("complexObjectFactory", ComplexObject.class);
System.out.println("Obtained object: " + complexObject);
// Get the FactoryBean itself
ComplexObjectFactoryBean factoryBean = (ComplexObjectFactoryBean) context.getBean("&complexObjectFactory");
System.out.println("Obtained FactoryBean: " + factoryBean);
}
}Corresponding XML configuration:
<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">
<!-- Define a Bean -->
<bean id="complexObjectFactory" class="com.qy.ComplexObjectFactoryBean">
<property name="propertyValue" value="test"/>
<property name="intPropertyValue" value="18"/>
</bean>
</beans>Usage Scenarios
BeanFactory usage scenarios:
As the foundational interface of the Spring IoC container.
Managing all beans in an application.
Providing bean lifecycle management and dependency injection.
FactoryBean usage scenarios:
Creating complex bean instances.
Integrating third‑party frameworks, e.g., MyBatis's SqlSessionFactoryBean.
Dynamically deciding which type of bean to return programmatically.
Performing preprocessing before returning a bean.
Xuanwu Backend Tech Stack
Primarily covers fundamental Java concepts, mainstream frameworks, deep dives into underlying principles, and JVM internals.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
