问题描述
Properties bean.properties
AccountService=com.itheima.service.impl.AccountServiceImpl
AccountDao=com.itheima.dao.impl.AccountDaoImpl
Properties bean.properties
accountService=com.itheima.service.impl.AccountServiceImpl
accountDao=com.itheima.dao.impl.AccountDaoImpl
public class BeanFactory {
private static Properties props;
private static Map beans;
static {
try {
props = new Properties();
InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
props.load(in);
beans = new HashMap();
Enumeration keys = props.keys();
while (keys.hasMoreElements()) {
String key = keys.nextElement().toString();
String beanPath = props.getProperty(key);
Object value = Class.forName(beanPath).newInstance();
beans.put(key, value);
}
} catch (Exception e) {
throw new ExceptionInInitializerError("初始化失败");
}
}
public static Object getBean(String beanName) {
return beans.get(beanName);
}
}
Dao层
public interface IAccountDao {
public void saveAccount();
}
public class AccountDaoImpl implements IAccountDao {
public void saveAccount() {
System.out.println("保存数据");
}
}
Service层
public interface IAccountSerivce {
//模拟保存
void saveAccount();
}
public class AccountServiceImpl implements IAccountSerivce {
private IAccountDao accountDao = (IAccountDao) BeanFactory.getBean("AccountDao");
public void saveAccount() {
accountDao.saveAccount();
}
}
主程序
public class Client {
public static void main(String[] args) {
for (int i = 0; i < 3; i++) {
IAccountSerivce as = (IAccountSerivce) BeanFactory.getBean("AccountService");
System.out.println(as);
as.saveAccount();
}
}
}
将propreties文件
AccountService=com.itheima.service.impl.AccountServiceImpl
AccountDao=com.itheima.dao.impl.AccountDaoImpl
大小写改成
accountService=com.itheima.service.impl.AccountServiceImpl
accountDao=com.itheima.dao.impl.AccountDaoImpl
即可运行
这是为什么?