实现一个自己的IOC
package com.IocExample; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /*** * @description: IoC容器例子 * @author: * @create: 2019-08-09 15:40 * * 1、实例化bean * 2、保存bean * 3、提供bean * 4、每一个ben要产生一个唯一的id与之相呼应 **/ public class IoCContainer { private Map<String, Object> beans = new ConcurrentHashMap<String, Object>(); /** * 根据beanId获取一个bean * @param beanId * @return 返回Bean */ public Object getBean(String beanId){ return beans.get(beanId); } /** * 委托IoC容器创建一个Bean * @param clazz 要创建的bean的class * @param beanId beanId * @param paramBeanId 要创建的bean的class的构造方法所需要的参数的beanId们(依赖的beanId) */ public void setBean(Class<?> clazz, String beanId,String... paramBeanId){ //1组装构造方法所需要的参数值--获取依赖bean Object[] paramValues = new Object[paramBeanId.length] ; for (int i = 0; i < paramBeanId.length; i++){ paramValues[i] = beans.get(paramBeanId[i]); System.out.println("paramValues["+ i + "] =" + paramValues[i]); } //2、调用构造方法实例化bean Object bean = null; //获取所有构造函数 for (Constructor<?> constructor : clazz.getConstructors()) { try{ bean = constructor.newInstance(paramValues); } catch (IllegalAccessException e) { } catch (InstantiationException e) { } catch (InvocationTargetException e) { } if (bean == null){ throw new RuntimeException("找不到合适的构造方法"); } } //3、将实例化的bean放入beans beans.put(beanId, bean); } }