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

    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();
            //Set designation here
            return employee;
            throw new IllegalArgumentException("Unknown product");

Use factory-method attribute for creating the beans.

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

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


Let’s test above static factory-method configuration.

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

        EmployeeDTO manager = (EmployeeDTO) context.getBean("manager");
        EmployeeDTO director = (EmployeeDTO) context.getBean("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


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