问题
我的properties文件
我的实现过程
#AccountDao接口
AccountDaoImpl实现类
AccountService接口
AccountServiceImpl实现类
Client类
BeanFactory类
package com.joey.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;
public class BeanFactory {
//定义一个Properties对象
private static Properties properties;
private static Map<String ,Object> beans;
//使用静态代码块为properties对象赋值
static{
try {
//实例化对象
properties = new Properties();
//获取properties文件的流对象
InputStream inputStream = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
properties.load(inputStream);
//实例化容器
beans = new HashMap<String, Object>();
//取出配置文件中的所有key
Enumeration keys = properties.keys();
//遍历枚举
while(keys.hasMoreElements()){
//取出每个Key
String key = keys.nextElement().toString();
//根据Key获取value
String beanPath = properties.getProperty(key);
//反射创建对象
Object value = Class.forName(beanPath).newInstance();
//把Key和Value存进容器
beans.put(key,value);
}
} catch (IOException e) {
throw new ExceptionInInitializerError("初始化properties失败");
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Object getBean(String beanName) {
return beans.get(beanName);
}
}
问题解决方法
把properties文件的两个配置换一下位置
分析
properties.load(inputStream)执行了这一步后,配置文件的两个配置的顺序已经反了
Object value = Class.forName(beanPath).newInstance();