Java如何通过工厂方法创建bean?

本示例说明如何在Spring Framework中使用工厂方法创建bean。我们将以单例为例。只能从工厂方法获取单例的实例,因为单例将具有私有构造函数,因此无法从单例本身之外创建此类的实例。

这是我们的单例豆外观。要获得它的实例,我们很需要调用该getInstance()方法。

package org.nhooo.example.spring.factory;

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() {
        System.out.println("Singleton.doSomething");
    }
}

接下来,我们将创建一个spring配置文件。最简单的是,配置文件中的Bean将具有id和class。要告诉spring容器使用工厂方法创建bean,我们必须使用factory-methodbean元素的属性。

这是我们的配置文件,我们为其命名factory-method.xml。

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

    <bean id="singleton"
          factory-method="getInstance">
    </bean>

</beans>

现在让我们在下面运行程序:

package org.nhooo.example.spring;

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

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

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