BeanFactory
package com.lichaozhang.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
public class BeanFactory {
private static Map<String, Object> beanMap = new HashMap<String, Object>();
static {
// 读取配置文件
Properties props = loadProperties("beans.properties");
// 生成所有对象的实例,放到 beanMap 中
for (Object key : props.keySet()) {
String name = (String) key;
String className = props.getProperty(name);
try {
// 生成实例
Object instance = Class.forName(className).newInstance();
// 放到beanMap中
beanMap.put(name, instance);
} catch (Exception e) {
throw new RuntimeException("初始化实例出错:" + name + " = " + className, e);
}
}
}
private static Properties loadProperties(String resource) {
Properties props = new Properties();
InputStream in = null;
try {
in = BeanFactory.class.getClassLoader().getResourceAsStream(resource);
props.load(in);
} catch (IOException e) {
throw new RuntimeException("加载配置文件出错:" + resource, e);
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return props;
}
/**
* 获取指定接口对应的实现类
*
* @param <T>
* @param clazz
* @return
*/
public static <T> T getBean(Class<T> clazz) {
return (T) beanMap.get(clazz.getSimpleName());
}
}
beans.properties
StoreDao=com.lichaozhang.dao.impl.StoreDaoImpl
StoreService
public interface StoreService {
}
StoreServiceImpl
public class StoreServiceImpl implements StoreService {
private StoreDao storeDao = BeanFactory.getBean(StoreDao.class);//BeanFactory用法
}
StoreDao
public interface StoreDao {
}
StoreDaoImpl
public class StoreDaoImpl implements StoreDao {
}