用工廠模式簡單實現spring的IOC容器

創建一個TestBean

package domain;

public class TestBean {
    private String name;
    public TestBean(){

    }
    public TestBean(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

創建工廠

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.*;

public class BeanFactory {
    private  Map<String,Object> map=new HashMap<String, Object>();
    private  InputStream in;
    private  Properties  p;
    private  String path;
    public BeanFactory(String propertiesPath){
        path=propertiesPath;
        init();
    }
    private void init(){
        try {
            in = new BufferedInputStream(BeanFactory.class.getClassLoader().getResourceAsStream(path));
            p = new Properties();
            p.load(in);
            Enumeration enumMap=p.propertyNames();
            while(enumMap.hasMoreElements()){
                String key=(String)enumMap.nextElement();
                String value=p.getProperty(key);
                Object clazz=Class.forName(value).newInstance();
                map.put(key,clazz);
            }
            System.out.println(p);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public  Object getBean(String id){
        return map.get(id);
    }


}

測試

import domain.TestBean;
public class App {
    public static void main(String[] args) {
        BeanFactory beanFactory= new BeanFactory("demo.properties");
        TestBean testBean=(TestBean)beanFactory.getBean("testBean");
        testBean.setName("op");
        System.out.println(testBean.getName());

    }
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章