手写一个BeanFactory创建对象工厂类

package utils;

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

/**
*创建bean对象的工厂
*
*
* bean 在计算机英语中  有可重用组件的含义
 */
public class BeanFactory {
    //            定义个properties对象
    private static Properties properties;
    /*
    * 用于存放bean实例的容器
    * */
    private static Map<String,Object> bean = new HashMap<String,Object>();
    static {
        try {

            properties= new Properties();
//            获取properties流对象
            InputStream resourceAsStream = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
//            加载类
            properties.load(resourceAsStream);
            Enumeration  keys = properties.keys();
//            枚举遍历
            while(keys.hasMoreElements()){
                String key = keys.nextElement().toString();
                System.out.printf(key);
                String beanPath = properties.getProperty(key);
                System.out.printf(beanPath);
//                使用反射创建对象
                Object o = Class.forName(beanPath).newInstance();
                bean.put(key,o);
            }
        } catch (Exception e) {
           throw new  ExceptionInInitializerError("初始化异常!");
        }

    }
    /**
     * 根据bean名称获取bean对象
    * */
    public  static  Object getBean(String beanName){
        return bean.get(beanName);
    }

}

猜你喜欢

转载自blog.csdn.net/qq_37950333/article/details/106631365
今日推荐