spring学习2:解耦--就是降低耦合

--工厂模式解耦

--定义一个Map,用于存放我们创建的对象,称为容器

**
* 一个创建bean对象的factory
* */

//配置文件选择properties
public class BeanFactory {
//定义一个properties对象
private static Properties props;

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

//使用静态代码块为Peoperties对象赋值
static {
try{
//实例化对象
props = new Properties();
//获取properties文件的流对象
//不要采用new FileInputStream,而采用下面的方法,因为以后的项目不保证他会有本地盘
InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.peoperties");
props.load(in);
//然后,实例化beans
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对象
* @param beanName
* @return
* 返回为Object
* */
public static Object getBean(String beanName){
return beans.get(beanName);
}

properties
accountService = com.itheima.service.AccountServiceImpl
accountDao = com.itheima.dao.impl.AccountDaoImpl

posted @ 2020-01-10 16:31  YKK1  阅读(277)  评论(0)    收藏  举报