Java Properties 实例化资源 有关于大小写出错

新手上路,请多包涵

问题描述

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<String, Object> beans;
    static {
        try {
            props = new Properties();
            InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
            props.load(in);
            beans = new HashMap<String, Object>();
            Enumeration<Object> 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
即可运行

这是为什么?

阅读 2.6k
1 个回答

你代码里写的是

private IAccountDao accountDao = (IAccountDao) BeanFactory.getBean("AccountDao");

配置文件中的 key 就应该写成AccountDao
我试着运行了你的代码,没有你说的问题

推荐问题