First create a singleton object through a static inner class
package com.spring.test.factorymethod; public class Stage { public void perform(){System.out .println ( " Show starts... " ); } private Stage(){ } private static class StageSingletonHolder{ static Stage instance = new Stage(); } public static Stage getInstance(){ return StageSingletonHolder.instance; } }
Specify the loaded method getInstance in the spring configuration file
<?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>
Call the bean to get the instance through the application context. Of course, you can also create other classes through the factory class, as long as you know what class to cast.
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(); } }