BeanFactory.java
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* 一个创建Bean对象的工厂
*/
public class BeanFactory {
//定义一个Properties对象
private static Properties pro;
//定义一个MAP,用于存放我们要创建的对象,称之为容器
private static Map<String,Object> beans;
//用静态代码给Properties负值
static {
try {
pro = new Properties();
//类加载器获取properties文件的对象
InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
pro.load(in);
//实例话容器
beans = new HashMap<String,Object>();
//读取配置文件的所有内容
//Enumeration接口中定义了一些方法,通过这些方法可以枚举(一次获得一个)对象集合中的元素。
//Enumeration:枚举
Enumeration keys = pro.keys();
//遍历枚举
while(keys.hasMoreElements()){
//获取key
String key = keys.nextElement().toString();
//根据key获取value
String beanPath = pro.getProperty(key);
//反射创建对象
Object value = Class.forName(beanPath).newInstance();
//把key存入容器
beans.put(key,value);
}
} catch (Exception e) {
throw new ExceptionInInitializerError("初始化失败aaa");
}
}
/**
* 根据bean的名称获取对象(单例)
*/
public static Object getBean(String beanName){
return beans.get(beanName);
}
/**
* 根据bean的名称获取对象(多例)
*/
// public static Object getBean(String beanName){
// Object bean = null;
// try {
// String beanPath = pro.getProperty(beanName);
// //利用反射获取bean
// bean = Class.forName(beanPath).newInstance();
// }catch (Exception e){
// e.printStackTrace();
// }
// return bean;
// }
}
bean.properties
accountDao = com.Ryuu.dao.impl.AccountDaoImpl
accountService = com.Ryuu.service.impl.AccountServiceImpl