Create bean objects through spring bean's factory-method

 

 First create a singleton object through a static inner class

copy code
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;
    }
}
copy code

  Specify the loaded method getInstance in the spring configuration file

copy code
<?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>
copy code

  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.

copy code
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();
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326753340&siteId=291194637