Spring static factory-method example

In Spring framework, if you want to create a bean by invoking a static factory-method, whose purpose is to encapsulate the object-creation process in a static method then you could use factory-method attribute.

Read More : Spring FactoryBean

Static factory method example

If you want to create different EmployeeDTO objects based on it’s designation using a static factory method, you can do it like below example.

public class EmployeeDTO {

    private Integer id;
    private String firstName;
    private String lastName;

    private String designation;

    //Setters and Getters

    @Override
    public String toString() {
        return "Employee [id=" + id + ", firstName=" + firstName
                + ", lastName=" + lastName + ", type=" + designation + "]";
    }
}

Create static factory method.

public class EmployeeFactory {
    
    public static EmployeeDTO createEmployeeOfType(String type) 
    {
        if ("manager".equals(type) || "director".equals(type)) 
        {
            EmployeeDTO employee = new EmployeeDTO();
            
            employee.setId(-1);
            employee.setFirstName("dummy");
            employee.setLastName("dummy");
            //Set designation here
            employee.setDesignation(type);
            
            return employee;
        }
        else
        {
            throw new IllegalArgumentException("Unknown product");
        }
    }
}

Use factory-method attribute for creating the beans.

<bean id="manager" class="com.howtodoinjava.demo.factory.EmployeeFactory"
    factory-method="createEmployeeOfType">
    <constructor-arg value="manager" />
</bean>

<bean id="director" class="com.howtodoinjava.demo.factory.EmployeeFactory"
    factory-method="createEmployeeOfType">
    <constructor-arg value="director" />
</bean>

Demo

Let’s test above static factory-method configuration.

public class TestSpringStaticFactoryMethod 
{
    @SuppressWarnings("resource")
    public static void main(String[] args) throws Exception 
    {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        EmployeeDTO manager = (EmployeeDTO) context.getBean("manager");
        System.out.println(manager);
        
        EmployeeDTO director = (EmployeeDTO) context.getBean("director");
        System.out.println(director);
    }
}

Watch the output in console.

Employee [id=-1, firstName=dummy, lastName=dummy, type=manager]
Employee [id=-1, firstName=dummy, lastName=dummy, type=director]

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

1 thought on “Spring static factory-method example”

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.