/**
* @author l
*1.实例化bean
*2.保存bean
*3.提供bean
*
*4.每个bean有一个唯一id
*/
public class IoCContainer {
private Map<String,Object> beans = new ConcurrentHashMap<String,Object>();
public Object getBean(String beanId) {
return beans.get(beanId);
}
/**
* 委托IOC容器创建一个bean
* 根据beanId获取一个bean
* @author l
*clazz:首先告诉IoC你要实例化的bean来源于哪个类/要创建的bean的class
*beanId:告诉IoC bean的id是什么
*paramBeanId:要创建的bean的class的构造方法所需要的参数的beanId们
*/
public void setBean(Class<?> clazz,String beanId,String... paramBeanIds) {
//组装构造方法所需的参数值
Object[] paramValues = new Object[paramBeanIds.length];
for(int i=0;i<paramBeanIds.length;i++) {
paramValues[i]=beans.get(paramBeanIds[i]);
}
//调用构造方法实例化bean
Object bean = null;
for(Constructor<?>constructor:clazz.getConstructors()) {
try {
bean = constructor.newInstance(paramValues);
}catch(InstantiationException e){
}catch(IllegalAccessException e) {
}catch(InvocationTargetException e) {
}
}
if(bean==null) {
throw new RuntimeException("找不到合适的构造方法实例化bean");
}
//将实例化的bean放入beans
beans.put(beanId, bean);
}
}