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
@Test
public 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