• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

How to create Spring Beans Using Spring FactoryBean

May 27, 2016 by javainterviewpoint Leave a Comment

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

Other interesting articles which you may like …

  • Spring Constructor Injection – Resolving Ambiguity
  • How to specify Spring Bean Reference and Spring Inner Bean
  • Spring Dependency Checking and Spring @Required Annotation
  • @Autowired, @Resource, @Qualifier, @Inject Annotation
  • Spring Bean Life Cycle – Bean Initialization and Destruction
  • Static Factory Method & Instance Factory Method
  • Spring PropertyPlaceholderConfigurer Example
  • Spring JdbcTemplate Example + JdbcDaoSupport
  • Spring CRUD Example with JdbcTemplate + Maven + Oracle
  • How to lazy initialize Spring beans?
  • How to change Spring Context Configuration file name

Filed Under: J2EE, Java, Spring, Spring Core, Spring Tutorial Tagged With: FactoryBean, Spring Bean, Spring FactoryBean

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·