2020.05.26 Spring中BeanFactory类

package com.aojie;

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

/**
* @author aojie
* @Function 是一个创建bean对象的工厂
* bean在计算机英语中有可重用组件的含义
* JavaBean:JavaBean!=实体类 用java语言编写的可重用组件
* 创建service和dao对象
* 第一步:需要一个配置文件来配置service和dao
* 配置内容:唯一标志=全限定类名(key-value的形式)
* 第二步:通过读取配置文件来反射创建对象
*
* 配置文件可以是xml也可以是properties
* @create 2020-05-26 21:40
*/
public class BeanFactory {
//定义一个properties对象
private static Properties properties;
//定义一个map用于存放要创建的对象,称之为容器
private static Map<String,Object> beans;
//使用静态代码块为properties对象赋值
static {
properties=new Properties();
try {
properties.load(BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties"));
//实例化容器
beans=new HashMap<String, Object>();
//取出配置文件中所有的key
Enumeration keys = properties.keys();
//遍历枚举
while(keys.hasMoreElements()){
String key = keys.nextElement().toString();
//根据key获取value
String beanPath=properties.getProperty(key);
Object value = Class.forName(beanPath).newInstance();
beans.put(key,value);
}
} catch (Exception e) {
throw new ExceptionInInitializerError("初始化properties失败!");
}
}
//根据BEAN的名称在MAP集合中获取对象
public static Object getBean(String beanName){
return beans.get(beanName);
}
//根据bean的名称获取对象
/*public static Object getBean(String beanName){
Object bean=null;
String beanPath=properties.getProperty(beanName);
try {
bean=Class.forName(beanPath).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return bean;
}*/
}

猜你喜欢

转载自www.cnblogs.com/aojie/p/12969325.html