Spring - BeanFactory

Last Updated : 25 Apr, 2026

Spring BeanFactory is the simplest container in the Spring framework that manages the creation and lifecycle of beans using dependency injection. It loads bean definitions and their dependencies at runtime based on configuration metadata. It acts as the basic IoC container and is the parent of ApplicationContext.

  • Instantiates, configures, and manages beans using XML or Java-based configuration.
  • Supports lazy loading of beans, creating them only when requested.
  • Does not support advanced features like annotation-based configuration (unlike ApplicationContext).

BeanFactory Interface classes Hierarchy

Hierarchy of spring container and its implementation showing the relationship between BeanFactory , ApplicationContext and various XML and Annotation-based context classes.

beanfactory
BeanFactory class Hierarchy

Some common methods Of BeanFactory

Let us first go through some of the methods of Bean Factory before landing up on implementation which are shown below in tabular format:

Method

Description

containsBean(String name)Does this bean factory contain a bean definition or externally registered singleton instance with the given name?
getAliases(String name)Return the aliases for the given bean name, if any.
getBean(Class<T> requiredType)Return the bean instance that uniquely matches the given object type, if any.
getBean(Class<T> requiredType, Object... args)Return an instance, which may be shared or independent, of the specified bean.
getBean(String name)Return an instance, which may be shared or independent, of the specified bean.
getBean(String name, Class<T> requiredType)Return an instance, which may be shared or independent, of the specified bean.
getBean(String name, Object... args)Return an instance, which may be shared or independent, of the specified bean.
getBeanProvider(Class<T> requiredType)Return a provider for the specified bean, allowing for lazy on-demand retrieval of instances, including availability and uniqueness options.
getBeanProvider(ResolvableType requiredType)Return a provider for the specified bean, allowing for lazy on-demand retrieval of instances, including availability and uniqueness options.
getType(String name)Determine the type of the bean with the given name.
getType(String name, boolean allowFactoryBeanInit)Determine the type of the bean with the given name.
isPrototype(String name)Is this bean a prototype? That is, will getBean(java.lang.String) always return independent instances?
isSingleton(String name)Is this bean a shared singleton? That is, will getBean(java.lang.String) always return the same instance?
isTypeMatch(String name, Class<?> typeToMatch)Check whether the bean with the given name matches the specified type.
isTypeMatch(String name, ResolvableType typeToMatch)Check whether the bean with the given name matches the specified type.

Procedure

  • First, create a Spring project using Spring Initializr
  • Create a POJO class.
  • Configure the Student bean in the bean-factory-demo.xml file.
  • Then write it to application class.

Project Structure

After creating all packages and classes, the project structure will look like below:

Folder-Structure

Steps to Configure Bean Factory in Spring

Follow these steps to configure and initialize the Spring BeanFactory in your application.

Step 1: Create a Student POJO class.

Defines the Student class as a POJO that will be managed as a Spring bean.

Student.java:

Java
// Java Program where we are
// creating a POJO class

// POJO class
public class Student {

  // Member variables
  private String name;
  private String age;

  // Constructor 1
  public Student() {
  }

  // Constructor 2
  public Student(String name, String age) {
    this.name = name;
    this.age = age;
  }

  // Method inside POJO class
  @Override
  public String toString() {

    // Print student class attributes
    return "Student{" + "name='" + name + '\'' + ", age='" + age + '\'' + '}';
  }
}

Step 2: Configure the Student bean in the bean-factory-demo.xml file.

Configures the Student bean in the XML file so the BeanFactory knows how to create it.

XML Bean Configuration:

XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans/"
        xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.springframework.org/schema/beans/
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="student" class="com.gfg.demo.domain.Student">
        <constructor-arg name="name" value="Tina"/>
        <constructor-arg name="age" value="21"/>
    </bean>
</beans>

Step 3: Now let's write the main class file.

Loads the BeanFactory and retrieves the Student bean from the container.

Java
@SpringBootApplication
// Main class
public class DemoApplication 
{
// Main driver method
  public static void main(String[] args) 
  {
    // Creating object in a spring container (Beans)
    BeanFactory factory = new ClassPathXmlApplicationContext("bean-factory-demo.xml");
    Student student = (Student) factory.getBean("student");

    System.out.println(student);
  }
}

Output:

Bean-Factory-Output

Explanation: The console output shows that the Student bean was successfully created by the BeanFactory and its values (name = Tina, age = 21) were correctly retrieved and displayed.

Note: XmlBeanFactory class is deprecated. 

Let's understand the above code with visuals:

Diagram to understand the flow

The program flow is something like this:

  • First of all, the Bean factory reads the XML configuration file and as per the specifications defined in it, it creates the bean of the student POJO.
  • Then the student reference asks for the student object from the object factory.
  • Then finally, the spring object factory hands over the spring bean (student) to its reference. Here, note that the bean returned by the object factory is of "Object" type, so we have to typecast it into our desired bean.

BeanFactory vs ApplicationContext

FeatureBeanFactoryApplicationContext
DefinitionBasic container for managing beansAdvanced container built on top of BeanFactory
Interface TypeRoot interfaceSub-interface of BeanFactory
Bean InitializationLazy loading (beans created when requested)Eager loading (beans created at startup by default)
PerformanceFaster startup, slower at runtimeSlower startup, better runtime performance
Dependency InjectionSupportedSupported
Bean Scope SupportBasic scopesSupports all scopes + web scopes
Event HandlingNot supportedSupports event publishing & listening
Internationalization (i18n)Not supportedSupported
Annotation SupportLimitedFull support (e.g., @Component, @Autowired)
AOP IntegrationLimitedFull support
Resource HandlingBasicAdvanced resource handling
Use CaseLightweight apps, memory-sensitive systemsEnterprise applications
Common ImplementationsXmlBeanFactory (Deprecated)ClassPathXmlApplicationContext, AnnotationConfigApplicationContext, WebApplicationContext
Recommended UsageRarely used nowWidely used in modern Spring apps
Comment

Explore