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 {
}