HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Spring Core / Spring static factory-method example

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?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Lakshman M

    May 12, 2017

    Can you make this example also in java-configuration equivalent for the XML code? Thank you.

  2. suda

    January 27, 2015

    Thank you!

Comments are closed on this article!

Search Tutorials

Spring Tutorial

  • Spring – Introduction
  • Spring – IoC Containers
  • Spring – IoC vs. DI
  • Spring – Bean Scopes
  • Spring – Bean Life Cycle
  • Spring – Bean Postprocessors
  • Spring – Autowiring
  • Spring – Annotations
  • Spring – Stereotype Annotations
  • Spring – Task Scheduling
  • Spring – Timer Task
  • Spring – Events
  • Spring – Message Source
  • Spring – ResourceLoader
  • Spring – Property Editor
  • Spring – Send Email
  • Spring – Version-less Schema
  • Spring – Interview Questions
  • Spring – Best Practices

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces