反射BeanFactory笔记

BeanFactory.java

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 一个创建Bean对象的工厂
 */
public class BeanFactory {

    //定义一个Properties对象
    private static Properties pro;
    //定义一个MAP,用于存放我们要创建的对象,称之为容器
    private static Map<String,Object> beans;

    //用静态代码给Properties负值
    static {
        try {
            pro = new Properties();
            //类加载器获取properties文件的对象
            InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
            pro.load(in);
            //实例话容器
            beans = new HashMap<String,Object>();
            //读取配置文件的所有内容
            //Enumeration接口中定义了一些方法,通过这些方法可以枚举(一次获得一个)对象集合中的元素。
            //Enumeration:枚举
            Enumeration keys = pro.keys();
            //遍历枚举
            while(keys.hasMoreElements()){
                //获取key
                String key = keys.nextElement().toString();
                //根据key获取value
                String beanPath = pro.getProperty(key);
                //反射创建对象
                Object value = Class.forName(beanPath).newInstance();
                //把key存入容器
                beans.put(key,value);
            }

        } catch (Exception e) {
            throw new ExceptionInInitializerError("初始化失败aaa");
        }
    }
    /**
     * 根据bean的名称获取对象(单例)
     */
    public static Object getBean(String beanName){
        return beans.get(beanName);
    }
    /**
     * 根据bean的名称获取对象(多例)
     */
//    public static Object getBean(String beanName){
//        Object bean = null;
//        try {
//            String beanPath = pro.getProperty(beanName);
//            //利用反射获取bean
//            bean = Class.forName(beanPath).newInstance();
//        }catch (Exception e){
//            e.printStackTrace();
//        }
//        return bean;
//    }

}

bean.properties

accountDao = com.Ryuu.dao.impl.AccountDaoImpl
accountService = com.Ryuu.service.impl.AccountServiceImpl
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值