/**
* 模拟spring容器如何创建实例
* (1) 提供一个config.properties配置文件,在这个文件中配置接口和实现类对应关系
* EmpService=com.tedu.EmpServiceImpl
* (2) 在当前类中读取 config.properties文件中的配置信息,将文件中的所有配置读取到
* Properties对象中
* (3) 提供一个getBean方法,接收接口名(例如:EmpService),根据接口名到Properties
* 对象中获取该接口对应的实现类的全限定类名(com.tedu.EmpServiceImpl),
* 在基于反射创建该类的实例,作为方法的返回值直接返回即可!
*
*/
public class BeanFactory {
//用于加载config.properties文件中的所有内容
private static Properties prop;
static {
try {
//初始化prop
prop = new Properties();
//获取指向config.properties文件的流对象
ClassLoader loader = BeanFactory.class.getClassLoader();//获取一个类加载器
InputStream in = loader.getResourceAsStream("config.properties");
//将config.properties文件中的所有内容加载prop对象中
prop.load( in );
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 根据接口名,到config.properties文件中获取该接口对应子类的全限定类名
* 再基于反射创建该子类的实例
* @param interName 接口名(也是config.properties文件中的key)
* @return Object 根据传入的接口名,返回该接口对应的子类实例
*/
public static Object getBean(String interName) {
try {
//根据接口名,到config.properties文件中获取该接口对应子类的全限定类名
String className = prop.getProperty( interName );
//通过子类的全限定类名获取该类的字节码对象
Class clz = Class.forName(className);
//在通过该类的字节码对象,获取该类的实例
Object obj = clz.newInstance();
return obj;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}