通过spring bean的factory-method创建bean对象

 首先通过静态内部类创建一个单例对象

复制代码
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();
    }
}

猜你喜欢

转载自xiaoxiaoher.iteye.com/blog/2396072