Bean creation mechanism, Instance Factory Method

Bean creation mechanism, Instance Factory Method

In normal case, we can use common mechanism through it’s constructor to create a bean and pass to spring container to manage Its lifecycle. But sometime when we deal with the legacy code or third party libraries that you have no control, spring provided the alternative way to use static or instance factory-method to obtain the instance.

How its work?

To use the class attribute to specific the name of the class that contains the static factory method, and specify the name of the actual method itself via the factory-method attribute.

CarFactory class has a factory method getCarBeanInstance(), this method has static modifier and it can be invoked without having CarFactory instance available in runtime. When factory-method applied, spring will directly invoke the static factory method to create the instance.

<bean id="carFactory" class="com.third.party.lib.CarFactory" factory-method="getCarBeanInstance"/>

package com.third.party.lib;
public class CarFactory {
    public static Car getCarBeanInstance() {
        return new Car();
    }
}

 

Non-static factory method

This example demonstrate you the container to get new bean instance similar like above example. It call a non-static factory method on different bean instance in the spring container. Refer to the snippet code below, when a new instance of carFactory is needed, spring container first create a CarFactory instance, and subsequent getCarBean method is called. We do not specify any value at all for the class attribute.  Once the new instance is obtained, the container will treat it the same regardless of which mechanism. That is, setter injection can be used and normal lifecycle callback will apply.

 

<bean id="carFactory" class="com.example.CarFactory">

<bean id="carBean" factory-bean="carFactory" factory-method="getCarBean"/>

public class CarFactory {

    public Car getCarBean() {
         return new Car();
    }
}

 

Spring’s FactoryBean Interface

You can use spring FactoryBean interface for bean creation. Example:

public class CarFactory implements FactoryBean<Car> {
    
    public Car getObject() throws Exception {
        Car car = new Car();
        car.setName("Toyota");
        return car;
    }

    public Class<?> getObjectType() {
        return Car.class;
    }

    public boolean isSingleton() {
        return true;
    }
}

 

Write a Reply or Comment

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