创建接口:
创建实现类:
创建配置文件这边为了好看我就 命名为bean.properties
创建工具类:
public class BeanFactory1 {
/**
* 加载解析properties文件
* 装载properties文件中的内容 <唯一标识,对象>
*/
private static Map<String, Object> map = new HashMap<String, Object>();
//ResourceBundle 加载配置文件
private static ResourceBundle bundle = ResourceBundle.getBundle("bean");
//在静态代码块实例化对象,并且存入map中
static {
Enumeration<String> keys = bundle.getKeys();
while (keys.hasMoreElements()){
String key = keys.nextElement(); //唯一标识
String classname = bundle.getString(key); //根据Key获取value
try {
Class clazz = Class.forName(classname);
Object value = clazz.newInstance();
map.put(key,value); //new AccountServiceImpl()
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static Object getBean(String id) throws Exception {
· return map.get(id);
}