package com.wanakiko.factory;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* @author WanAkiko
* @create-time 2021-05-16
*/
public class BeanFactory {
// 定义属性文件对象
private static Properties props;
// 定义存放对象的容器
private static Map<String, Object> beansContainer;
// 定义字节输入流对象
private static InputStream inputStream;
static {
try {
// 实例化属性文件对象
props = new Properties();
// 字节流读取属性文件
inputStream = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
// 将字节流读取到的内容转交给属性文件对象
props.load(inputStream);
// 实例化容器对象
beansContainer = new HashMap<String, Object>();
// 获取配置文件中的key
Enumeration<Object> 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转存至容器中
beansContainer.put(key, value);
}
} catch (IOException e) {
throw new ExceptionInInitializerError("Failed to initialize the properties file.");
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 根据给定的BeanName获取Bean对象
* @param beanName 名称参数
* @return Bean对象
*/
public static Object getFactoryBean(String beanName) {
return beansContainer.get(beanName);
}
}