当然userdao,bookdao必须存在,自己建出来,我就不贴了,下面贴核心的BeanFactory类:
package com.tmaic.util;
import java.io.IOException;
import java.util.Properties;
public class BeanFactory {
static Properties pro;
//读取配置文件
static {
pro = new Properties();
try {
pro.load(BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static Object getBean(String key) {
if(pro.containsKey(key)){
//获取完全限定名
String className = pro.getProperty(key);
//通过反射,创建对象
Object obj = null;
try {
obj = Class.forName(className).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}else{
throw new IllegalArgumentException("key不存在");
}
}
}
需要说明的是,上面的程序是懒加载,当请求对象时对象才会创建出来;
如果想实现非懒加载,我们要在读取配置文件的时候就把对象给创建出来,如果你有这样的需求,可以迭代pro中的key来一一创建出对象:
贴下迭代的部分:
public class BeanFactory {
private static Map map = new HashMap();
private static Properties pro;
//读取配置文件
static {
pro = new Properties();
try {
pro.load(BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties"));
for(Entry entry:pro.entrySet()){
String key = entry.getKey().toString();
Object obj = Class.forName(entry.getValue().toString()).newInstance();
map.put(key, obj);
}
} catch (Exception e) {
e.printStackTrace();
}
}