手动实现工厂类:
- 读取properties文件,并利用Map保存Bean实现单例模式。
- 使用时利用getBean方法创建对象
public class BeanFactory {
private static Properties properties;
private static Map<String , Object> beans;
static {
try {
//实例化对象
properties = new Properties();
//获取properties文件流对象
InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
properties.load(in);
beans=new HashMap<String, Object>();
Enumeration keys=properties.keys();
while(keys.hasMoreElements()){
//取出每个key
String key=keys.nextElement().toString();
//根据key获取value
String keyPath=properties.getProperty(key);
System.out.println(keyPath);
//根据keyPath创建反射对象
Object value=Class.forName(keyPath).newInstance();
//放入map
beans.put(key,value);
}
}catch (Exception e){
throw new ExceptionInInitializerError("初始化properties失败!");
}
}
public static Object getBean(String beanName){
return beans.get(beanName);
}
}
bean.properties
accountService=com.chajiu.service.AccountServicelmpl
accountDao=com.chajiu.dao.AccountDAOlmpl
创建对象:
IAccountService service = (IAccountService) BeanFactory.getBean("accountService");
网友评论