How do I create beans through factory method?

This example show you how to create a bean using factory method in Spring Framework. We will use a singleton as an example. An instance of a singleton can be obtained only from a factory method because a singleton will have a private constructor so it will not possible to create an instance of this class from outside the singleton itself.

Here is our singleton bean will look like. To get an instance of it we well need to call the getInstance() method.

package org.kodejava.example.spring;

public class Singleton {

     * Private constructor.
    private Singleton() {

    private static class SingletonHolder {
        static Singleton instance = new Singleton();

     * Get an instance of Singleton class.
     * @return an instance of Singleton class.
    public static Singleton getInstance() {
        return SingletonHolder.instance;

     * Do something.
    public void doSomething() {

Next, we will create a spring configuration file. At it simplest a bean in the configuration file will have an id and a class. To tell the spring container to create the bean using a factory method we must use the factory-method attribute of the bean element.

Here is our configuration file and we name it FactoryMethod.xml.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

    <bean id="singleton" class="org.kodejava.example.spring.Singleton"


Let’s now run our program below:

package org.kodejava.example.spring;

import org.springframework.context.ApplicationContext;

public class FactoryMethodDemo {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("FactoryMethod.xml");

        Singleton instance =
                (Singleton) context.getBean("singleton");

Wayan Saryada

Programmer, runner, recreational diver, currently living in the island of Bali, Indonesia. Mostly programming in Java, creating web based application with Spring Framework, Hibernate / JPA.

Leave a Reply