The Wayback Machine - https://web.archive.org/web/20240529104040/https://www.geeksforgeeks.org/spring-beanfactory/
Open In App

Spring – BeanFactory

Last Updated : 01 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The first and foremost thing when we talk about Spring is dependency injection which is possible because Spring is a container and behaves as a factory of Beans. Just like the  BeanFactory interface is the simplest container providing an advanced configuration mechanism to instantiate, configure, and manage the life cycle of beans.

Beans are Java objects that are configured at run-time by Spring IoC Container. BeanFactory represents a basic IoC container which is a parent interface of ApplicationContext. BeanFactory uses Beans and their dependencies metadata to create and configure them at run-time. BeanFactory loads the bean definitions and dependency amongst the beans based on a configuration file (XML) or the beans can be directly returned when required using Java Configuration. There are other types of configuration files like LDAP, RDMS, properties files, etc. BeanFactory does not support Annotation-based configuration whereas ApplicationContext does.

Spring Container

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 start.spring.io.
  • 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

Step-by-Step Implementation to Configure Bean Factory in Spring

Step 1: Create a Student POJO class.

Now we will define bean inside the Student class file.

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.

XML Bean Configuration:

XML
<?xml version="1.0" encoding="UTF-8"?>
<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
        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.

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:

Student{name='Tina', age='21'}

Bean-Factory-Output

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.


Previous Article
Next Article

Similar Reads

Spring - Difference Between BeanFactory and ApplicationContext
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE developers to build simple, reliable, and scalable enterprise applications. It provides Aspect-oriented programming. It provides support for all generic and middleware services and mainly focuses on providing various ways to help you
10 min read
Spring Boot - Spring JDBC vs Spring Data JDBC
Spring JDBC Spring can perform JDBC operations by having connectivity with any one of jars of RDBMS like MySQL, Oracle, or SQL Server, etc., For example, if we are connecting with MySQL, then we need to connect "mysql-connector-java". Let us see how a pom.xml file of a maven project looks like. C/C++ Code &lt;?xml version=&quot;1.0&quot; encoding=
4 min read
Difference Between Spring DAO vs Spring ORM vs Spring JDBC
The Spring Framework is an application framework and inversion of control container for the Java platform. The framework's core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring-DAO Spring-DAO is not a spring module. It does not provide interfaces or templates
5 min read
Java Spring Boot Microservices - Develop API Gateway Using Spring Cloud Gateway
The API Gateway Pattern in some cases stands for “Backend for frontend”. It is basically the entry gate for taking entry into any application by an external source. The pattern is going on in a programmer’s mind while they are making the client’s application. It acts as a medium between the client applications and microservices. For example-Netflix
4 min read
Spring Boot | How to access database using Spring Data JPA
Spring Data JPA is a method to implement JPA repositories to add the data access layer in applications easily. CRUD stands for create, retrieve, update, delete which are the possible operations which can be performed in a database. In this article, we will see an example of how to access data from a database(MySQL for this article) in a spring boot
4 min read
Difference between Spring MVC and Spring Boot
1. Spring MVC : Spring is widely used for creating scalable applications. For web applications Spring provides Spring MVC framework which is a widely used module of spring which is used to create scalable web applications. Spring MVC framework enables the separation of modules namely Model View, Controller, and seamlessly handles the application in
3 min read
Spring - Add User Name and Password in Spring Security
Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications. Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is fou
3 min read
Spring - Add Roles in Spring Security
Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications. Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is fou
4 min read
Spring - Shortcut to Create Dispatcher Servlet in Eclipse/Spring Tool Suite
Eclipse is an Integrated Development Environment (IDE) used in computer programming. It includes a base workspace and an extensible plug-in system for customizing the environment. It is the second-most-popular IDE for Java development. Eclipse is written mostly in Java and its primary use is for developing Java applications, but it may also be used
4 min read
Spring - Integration of Spring 4, Struts 2, and Hibernate
In modern Java web application development, integrating different frameworks is a common requirement to leverage the strengths of each framework. Spring, Struts, and Hibernate are three popular frameworks that can work together seamlessly to build robust and scalable applications. In this article, we will explore how to integrate Spring 4, Struts 2
4 min read