首先通过静态内部类创建一个单例对象
package com.spring.test.factorymethod; public class Stage { public void perform(){ System.out.println("演出开始..."); } private Stage(){ } private static class StageSingletonHolder{ static Stage instance = new Stage(); } public static Stage getInstance(){ return StageSingletonHolder.instance; } }
在spring配置文件中指定加载的方法getInstance
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="theStage" class="com.spring.test.factorymethod.Stage" factory-method="getInstance"></bean> </beans>
通过应用上下文调用bean获取实例 当然也可以通过factory类创建其他类只要你知道要强转为什么类就行
package com.spring.test.factorymethod; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class test { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml"); Stage stage = ((Stage)ctx.getBean("theStage"));//.getInstance(); stage.perform(); } }