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 !!

Leave a Reply

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial