Spring static factory-method Example

In spring, developers can create a bean (or the object instantiation) by invoking the static-factory-method. This tutorial will explore the use of factory-method attribute in the spring configuration file.

  • The factory-method attribute is used when the factory-method is static in nature

1. Introduction

  • Spring is an open-source framework created to address the complexity of an enterprise application development
  • One of the chief advantages of the Spring framework is its layered architecture, which allows the developer to be selective about which of its components they can use while providing a cohesive framework for J2EE application development
  • Spring framework provides support and integration to various technologies for e.g.:
    • Support for Transaction Management
    • Support for interaction with the different databases
    • Integration with the Object Relationship frameworks for e.g. Hibernate, iBatis etc
    • Support for Dependency Injection which means all the required dependencies will be resolved with the help of containers
    • Support for REST style web-services

Now, open up the Eclipse IDE and let us see how to implement this attribute in the spring framework!

2. Spring static factory-method Example

Here is a systematic guide for implementing this tutorial in the spring framework.

2.1 Tools Used

We are using Eclipse Kepler SR2, JDK 8 and Maven. Having said that, we have tested the code against JDK 1.7 and it works well.

2.2 Project Structure

Firstly, let us review the final project structure, in case you are confused about where you should create the corresponding files or folder later!

Spring static factory-method - Application Project Structure
Fig. 1: Application Project Structure

2.3 Project Creation

This section will demonstrate how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Spring static factory-method - Create a Maven Project
Fig. 2: Create a Maven Project

In the New Maven Project window, it will ask you to select a project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ checkbox and just click on the next button to proceed.

Spring static factory-method - Project Details
Fig. 3: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Spring static factory-method - Archetype Parameters
Fig. 4: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you observe, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

We can start adding the dependencies that developers want like Spring Core, Spring Context etc. Let us start building the application!

3. Application Building

Below are the steps involved in developing this application.

3.1 Maven Dependencies

Here, we specify the dependencies for the spring framework. Maven will automatically resolve the rest dependencies such as Spring Beans, Spring Core etc. The updated file will have the following code:


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<name>Spring Static Factory Method Example</name>
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
		<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->

3.2 Java Class Creation

Let us write the Java classes involved in this application.

3.2.1 Implementation of Bean class

Add the following code to the bean definition.


package com.spring.model;

public class School {

	private int id;
	private String name;
	private String location;

	public int getId() {
		return id;
	public void setId(int id) {
		this.id = id;
	public String getName() {
		return name;
	public void setName(String name) {
		this.name = name;
	public String getLocation() {
		return location;
	public void setLocation(String location) {
		this.location = location;

	public String toString() {
		return "*** School Details ***\n Id= " + id +"\n " + "Name= " + name + "\n Location= " + location + "\n ";

3.2.2 Implementation of Factory class

Add the following code to the factory class.


package com.spring.factory;

import com.spring.model.School;

public class SchoolFactory {

	public static School getSchool(String loc) {

		School school = null;

		if(loc.equalsIgnoreCase("Vikaspuri")) {

			school = new School();
			school.setName("Oxford Senior Secondary School");

		} else if (loc.equalsIgnoreCase("Janakpuri")) {

			school = new School();
			school.setName("Stanford Public School");
		} else {
			throw new IllegalArgumentException("Unknown school");

		return school;

3.2.3 Implementation of Utility Class

Add the following code to the implementation class for testing the static factory-method configuration.


package com.spring.util;

import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.model.School;

public class AppMain {

	public static void main(String[] args) {

		// Reading the spring configuration file!
		AbstractApplicationContext ac = new ClassPathXmlApplicationContext("spring-staticfactory.xml");

		School s = (School) ac.getBean("oxford");

		School s1 = (School) ac.getBean("stanford");


3.3 Bean Configuration file

In the spring xml configuration, we’ll use the factory-method attribute for the beans creations.


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

	<bean id="oxford" class="com.spring.factory.SchoolFactory"
		<constructor-arg value="Vikaspuri" />

	<bean id="stanford" class="com.spring.factory.SchoolFactory"
		<constructor-arg value="Janakpuri" />

4. Run the Application

To execute the application, right click on the AppMain class, Run As -> Java Application. Developers can debug the example and see what happens after every step. Enjoy!

Spring static factory-method - Run the Application
Fig. 5: Run the Application

5. Project Demo

The code shows the following log as the output of this tutorial.

Oct 20, 2018 3:28:16 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-staticfactory.xml]

*** School Details ***
 Id= 1001
 Name= Oxford Senior Secondary School
 Location= Vikaspuri
*** School Details ***
 Id= 1002
 Name= Stanford Public School
 Location= Janakpuri
Oct 20, 2018 3:28:16 PM org.springframework.context.support.AbstractApplicationContext doClose

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

6. Conclusion

This post defines the implementation of the factory-method attribute in the spring framework and helps developers understand the basic configuration required to achieve this. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the Eclipse Project

This was an example of spring static factory-method for beginners.

You can download the full source code of this example here: SpringStaticFactoryMethod


An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Notify of

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

Inline Feedbacks
View all comments
Back to top button