bean.properties 用来存放实现类的全限定路径

accountService=com.wyatt.service.impl.AccountServiceImpl
accountMapper=com.wyatt.mapper.impl.AccountMapperImpl

BeanFactory.java 定义一个 Map 用于存放要创建的对象,key 存放类名,value 存放对应的对象

public class BeanFactory {
    //定义Properties对象
    private static Properties props;
    //定义一个Map用于存放我们要创建的对象,我们把它称之为容器
    private static Map<String, Object> beans;
 
    //使用静态代码块为Properties对象赋值
    static {
        try {
            props = new Properties();
            //获取Properties文件的流对象
            InputStream is = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
            props.load(is);
            //实例化我们的容器
            beans = new HashMap<String, Object>();
            //取出配置文件中所有的key
            Enumeration keys = props.keys();
            //遍历枚举
            while(keys.hasMoreElements()) {
                //取出每个key
                String key = keys.nextElement().toString();
                //根据key获取value
                String beanPath = props.getProperty(key);
                //反射创建对象
                Object value = Class.forName(beanPath).newInstance();
                //把key和value存入容器中
                beans.put(key, value);
            }
        } catch (Exception e) {
            throw new ExceptionInInitializerError("初始化properties失败!");
        }
    }
 
    //根据bean名称获取bean对象
    //beans是一个Map,根据key获取value
    public static Object getBean(String beanName) {
        return beans.get(beanName);
    }
 
    //根据bean名称获取bean对象
    /*public static Object getBean(String beanName) {
        Object bean = null;
        String beanPath  = props.getProperty(beanName);
        try {
            bean = Class.forName(beanPath).newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
    }*/
}

Client.java

模拟表现层,用于调用业务层

public class Client {
    public static void main(String[] args) {
        //使用工厂模式创建对象
        //getBean返回的是Object对象,所以需要强制类型转换
        IAccountService as = (IAccountService)BeanFactory.getBean("accountService");
        as.saveAccount();
    }
}