工厂创建Bean对象(单例、多例)

目录结构:
在这里插入图片描述

package com.itheima.factory;

import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 一个创建Bean对象的工厂
 *
 * Bean在计算机英语中有可重用组件的含义
 *
 */
public class BeanFactory {

    //定义一个Properties对象
    private static Properties props;

    //定义一个Map,用于存放我们要创建的对象。我们把它称之为容器
    private static Map<String,Object> beans;

    //使用静态代码块为Properties对象赋值
    static {
        try {
            //实例化对象
            props = new Properties();
            //获取properties文件的流对象
           // InputStream in = BeanFactory.class.getResourceAsStream("/bean.properties");
          //  InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
          //  InputStream in = new BeanFactory().getClass().getResourceAsStream("/bean.properties");
            InputStream in = new BeanFactory().getClass().getClassLoader().getResourceAsStream("bean.properties");

            props.load(in);
            //实例化容器
            beans = new HashMap<String, Object>();
            //取出配置文件中所有的key
            Enumeration keys = props.keys();
            //遍历枚举
            while (keys.hasMoreElements()){
                //取出每个key
                String key = keys.nextElement().toString();
                //根据key获取value
                String beanPath = props.getProperty(key);
                //反射加载创建对象
                Object value = Class.forName(beanPath).newInstance();
                //把key和value存入容器
                beans.put(key,value);
            }
        }catch(Exception e){
          //  throw new ExceptionInInitializerError("初始化properties文件失败");
            e.printStackTrace();
        }
    }

    /**
     * 根据bean的名称获取对象
     * 从map中取的对象,单例对象
     * @param beanName
     * @return
     */
    public static Object getBean(String beanName){
        return beans.get(beanName);
    }

    /**
     * 根据bean的名称获取bean对象
     * 每次调用都要new一个Instance,是多例对象
     * @param beanName
     * @return
     */
 /*   public static Object getBean(String beanName){
        Object bean = null;
        try {
            String beanPath = props.getProperty(beanName);
            bean = Class.forName(beanPath).newInstance();
        }catch(Exception e){
            e.printStackTrace();
        }
        return bean;
    }*/
}

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
结果:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_34721292/article/details/89928904