spring学习笔记(17)--通过工厂方法创建Bean

来源:互联网 发布:flash builder java 编辑:程序博客网 时间:2024/04/28 03:38

1.beans.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-2.5.xsd">  <bean id="theStage" class="com.springinaction.springidol.Stage" factory-method="getInstance">  </bean></beans>
Stage.java

public class Stage {private Stage(){}static class StageSingletonHolder{static Stage instance = new Stage();}public static Stage getInstance(){return StageSingletonHolder.instance;}}
StageTest.java

@Testpublic void testGetInstance() {ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");Stage stage = (Stage) ctx.getBean("theStage");Stage stage1 = (Stage) ctx.getBean("theStage");System.out.println(stage == stage1);}

测试结果:true



0 0
原创粉丝点击