How to create Spring Beans Using Spring FactoryBean

In Spring you can also Create and Configure of Spring Bean using Spring’s FactoryBean . A factory bean in Spring serves as a factory for creating other beans within the Spring IoC container. In Java terms we can say that, a factory bean is very similar to a factory method (Java Factory Pattern), but here it is Spring specific bean which can be identified by the Spring IoC container during bean construction.

Need for Spring FactoryBean ?

In order to create a bean we need to implement the interface “FactoryBean”. For our convenience Spring have also provided an Abstract Class “AbstractFactoryBean” which we can extend. You simply has to override createInstance() and getObjectType() methods

createInstance() :  This method is used create the bean instance

getObjectType() : This method returns the class type of the target instance, this method is required for the auto-wiring feature to work properly.

Factory is mostly used to implement framework specific operations.

  1. Suppose when you are looking for JNDI related stuffs then JndiObjectFactoryBean can be used.
  2. For Spring AOP related stuffs (create a proxy for a bean) we can use ProxyFactoryBean.
  3. For creating Hibernate Session Factory in the Spring IoC container then we can use LocalSessionFactoryBean.

Spring FactoryBean Example

Folder Structure:

  1. Create a new Java Project  SpringCoreTutorial” and create a package for our src files com.javainterviewpoint
  2. Add the required libraries to the build path. Java Build Path ->Libraries ->Add External JARs and add the below jars.

    commons-logging-1.2.jar
    spring-beans-4.2.4.RELEASE.jar
    spring-core-4.2.4.RELEASE.jar
    spring-context-4.2.4.RELEASE.jar
    spring-expression-4.2.4.RELEASE.jar

  3. Create the Java classes Vehicle.java, Car.java, Bus.java, VehicleFactoryBean.java and VehicleLogic.java under  com.javainterviewpoint folder.
  4. Place our configuration file SpringConfig.xml in the src directory

Bean Classes

Vehicle.java

package com.javainterviewpoint;

public class Vehicle
{
    private String name;
    private String color;
    
    public Vehicle()
    {
        super();
    }
    public Vehicle(String name, String color)
    {
        super();
        this.name = name;
        this.color = color;
    }

    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public String getColor()
    {
        return color;
    }
    public void setColor(String color)
    {
        this.color = color;
    }
}

Car.java

package com.javainterviewpoint;

public class Car extends Vehicle
{
    private int enginePower;
    
    public Car()
    {
        super();
    }
    public Car(String name,String color)
    {
        super(name,color);
    }
    public int getEnginePower()
    {
        return enginePower;
    }

    public void setEnginePower(int enginePower)
    {
        this.enginePower = enginePower;
    }
}

Bus.java

package com.javainterviewpoint;

public class Bus extends Vehicle
{
    private int noOfWheels;
    
    public Bus()
    {
        super();
    }
    public Bus(String name,String color)
    {
        super(name,color);
    }
    public int getNoOfWheels()
    {
        return noOfWheels;
    }

    public void setNoOfWheels(int noOfWheels)
    {
        this.noOfWheels = noOfWheels;
    }
}

VechicleFactoryBean.java

package com.javainterviewpoint;

import org.springframework.beans.factory.config.AbstractFactoryBean;

public class VehicleFactoryBean extends AbstractFactoryBean
{
    private Vehicle vehicle;

    public Vehicle getVehicle()
    {
        return vehicle;
    }

    public void setVehicle(Vehicle vehicle)
    {
        this.vehicle = vehicle;
    }

    @Override
    protected Object createInstance() throws Exception
    {
        return vehicle;
    }

    @Override
    public Class getObjectType()
    {
        return Vehicle.class;
    }

}
  • In the VehicleFactoryBean we have extended AbstractFactroyBean class
  • We have getters and setters for the property “vehicle”
  • We are overriding two methods of the AbstractFactroyBean class createInstance() and getObjectType() methods. createInstance() method returns the vehicle object and getObjectType() method returns the class of Vehicle.

Declaring Bean Configuration File (SpringConfig.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="car" class="com.javainterviewpoint.VehicleFactoryBean">
   <property name="vehicle">
     <bean class="com.javainterviewpoint.Car">
       <constructor-arg value="BMW" />
       <constructor-arg value="White" />
       <property name="enginePower" value="1000"></property>
     </bean>
   </property>
 </bean>
 
 <bean id="bus" class="com.javainterviewpoint.VehicleFactoryBean">
   <property name="vehicle">
     <bean class="com.javainterviewpoint.Bus">
       <constructor-arg value="VolvoBus" />
       <constructor-arg value="Red" />
       <property name="noOfWheels" value="6"></property>
     </bean>
   </property>
 </bean>
</beans>
  • We have declared the two bean ids “car”, “bus” for the same VehicleFactoryBean class
  • For the property “vehicle” we are injecting a inner bean of Car and Bus class respectively, passing values to the constructor (Constructor Injection) and setter (Setter Injection)

Instantiating Spring IoC Container – Application Context

Since ApplicationContext is an interface, Here we need to instantiate an implementation of it. We will instantiate ClassPathXmlApplicationContext implementation which builds an application context by loading an XML configuration file from the classpath.

package com.javainterviewpoint;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class VehicleLogic
{
    public static void main(String args[]) throws Exception
    {
        // Read the Configuration file using ApplicationContext
        ApplicationContext applicationContext = 
                new ClassPathXmlApplicationContext("SpringConfig.xml");

        // Get the Car instance from factory
        Car c = (Car) applicationContext.getBean("car");
        System.out.println("Car Name     : " + c.getName());
        System.out.println("Car Color    : " + c.getColor());
        System.out.println("Car Engine CC: " + c.getEnginePower());

        // Get the Bus instance from factory
        Bus b = (Bus) applicationContext.getBean("bus");
        System.out.println("Bus Name     : " + b.getName());
        System.out.println("Bus Color    : " + b.getColor());
        System.out.println("Bus Wheels: " + b.getNoOfWheels());
    }
}
  • In our VehicleLogic class we have read the Configuration file(SpringConfig.xml) and get all the bean definition through ApplicationContext
  • Get the Car and Bus Class instance by calling the getBean() method over the context created. Even though we have created bean for VehicleFactoryBean we will be getting the required instance(Car , Bus) from the factory though.
  • Print the values of the individual properties of each instances.

Output :

Spring FactoryBean Example

Leave a Reply

Your email address will not be published. Required fields are marked *