现在的位置: 首页 > 综合 > 正文

自己实现的简单IOC

2014年02月02日 ⁄ 综合 ⁄ 共 8297字 ⁄ 字号 评论关闭

public class BeanDefinition {

    private String id; // 对应 spring配置文件中的id
    private String className; // 对应 spring配置文件中的class

    // 定义 bean中 属性的节点 集合
    private List<PropertyDefinition> propertys = new ArrayList<PropertyDefinition>();

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public List<PropertyDefinition> getPropertys() {
        return propertys;
    }

    public void setPropertys(List<PropertyDefinition> propertys) {
        this.propertys = propertys;
    }

    public BeanDefinition() {
    }

    public BeanDefinition(String id, String className) {
        this.id = id;
        this.className = className;
    }

}

public class PropertyDefinition {
    private String name; // 对应配置 文件中的name
    private String ref; // 对应配置 文件中的ref
    private String value; // 为基本属性注入值
    private List<String> lists; // lists 注入
    private Map<String,String> maps;

    public List<String> getLists() {
        return lists;
    }

    public void setLists(List<String> lists) {
        this.lists = lists;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getRef() {
        return ref;
    }

    public void setRef(String ref) {
        this.ref = ref;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public Map<String, String> getMaps() {
        return maps;
    }

    public void setMaps(Map<String, String> maps) {
        this.maps = maps;
    }

    public PropertyDefinition() {
        super();
        // TODO Auto-generated constructor stub
    }

    public PropertyDefinition(String name, String ref) {
        super();
        this.name = name;
        this.ref = ref;
    }

    public PropertyDefinition(String name, String ref, String value) {
        super();
        this.name = name;
        this.ref = ref;
        this.value = value;
    }

    public PropertyDefinition(String name, String ref, String value,
            List<String> lists,Map<String,String> maps) {
        super();
        this.name = name;
        this.ref = ref;
        this.value = value;
        this.lists = lists;
        this.maps = maps;
    }

}

public class MySpringClassPathXmlApplicationContext1 {

    private List<BeanDefinition> beandefines = new ArrayList<BeanDefinition>();// 从配置文件得到的bean对象

    private Map<String, Object> sigletons = new HashMap<String, Object>();

    public MySpringClassPathXmlApplicationContext1(String fileName) {

        this.readXml(fileName);

/*        for (BeanDefinition b : beandefines) {
            for (PropertyDefinition p : b.getPropertys()) {
                if (p.getLists() != null) {
                    for (String s : p.getLists()) {
                        System.out.println("!@!" + s);
                    }
                }
            }
        }*/
        this.instanceBean();// 初始化bean
        this.injectObject();// 注入
    }

    public void readXml(String fileName) {
        fileName = Thread.currentThread().getContextClassLoader().getResource(
                fileName).getPath().substring(1);
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(new File(fileName));// 读取XML文件
            Iterator<?> beans = document.getRootElement().elementIterator(
                    "bean");
            while (beans.hasNext()) {
                Element element = (Element) beans.next();
                String id = element.attributeValue("id");
                String clazz = element.attributeValue("class");
                BeanDefinition beanDefinition = new BeanDefinition(id, clazz);

                Iterator<?> propertyDefinition = element.elementIterator();
                while (propertyDefinition.hasNext()) {
                    List<String> listValues = null;
                    Map<String,String> mapValues = null;
                    Element property = (Element) propertyDefinition.next();

                    Iterator<?> collections = property.elementIterator();
                    while (collections.hasNext()) {// 得到property所有list这个标签
                        Element collection = (Element) collections.next();

                        String collectionType = collection.getName();
                        if (collectionType.equals("set")
                                || collectionType.equals("list")) {
                            Iterator<?> values = collection.elementIterator();
                            listValues = new ArrayList<String>();
                            while (values.hasNext()) {// 得到list所有value这个标签的值得
                                Element listValue = (Element) values.next();
                                String valueList = listValue.getText();
                                listValues.add(valueList);
                            }
                        }else if(collectionType.equals("map")){
                            Iterator<?> values = collection.elementIterator();
                            mapValues = new HashMap<String,String>();
                            while (values.hasNext()) {// 得到list所有value这个标签的值得
                                Element mapValue = (Element) values.next();
                                String key = mapValue.attributeValue("key");
                                String value = mapValue.attributeValue("value");
                                mapValues.put(key, value);
                            }
                        }else{
                            throw new Exception("配置错误,只能set list map");
                        }
                    }
                    String name = property.attributeValue("name");
                    String value = property.attributeValue("value");
                    String ref = property.attributeValue("ref");
                    PropertyDefinition propertyBean = new PropertyDefinition(
                            name, ref, value, listValues,mapValues);
                    beanDefinition.getPropertys().add(propertyBean);
                }
                beandefines.add(beanDefinition);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void instanceBean() {
        for (BeanDefinition beandefine : beandefines) {
            if (beandefine.getClassName() != null
                    && !beandefine.getClassName().equals("")) {
                try {
                    sigletons.put(beandefine.getId(), Class.forName(
                            beandefine.getClassName()).newInstance());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void injectObject() {
        try {
            for (BeanDefinition beanDefinition : beandefines) {
                Object bean = sigletons.get(beanDefinition.getId());
                if (bean != null) {
                    // 如果对象不为空 就获取这个对象的 所有属性信息
                    PropertyDescriptor[] ps = Introspector.getBeanInfo(
                            bean.getClass()).getPropertyDescriptors();
                    for (PropertyDefinition propertyDefinition : beanDefinition// 如果没有这个说明只是个bean定义,没有依赖注入的值
                            .getPropertys()) {
                        for (PropertyDescriptor pd : ps) {
                            if (propertyDefinition.getName().equals(
                                    pd.getName())) {// 类里定义的属性和XML定义的属性相同
                                Method methodSetter = pd.getWriteMethod();
                                if (methodSetter != null) {
                                    Object value = null;
                                    if (!methodSetter.isAccessible()) {
                                        methodSetter.setAccessible(true);// 如果私有方法则设置成可以访问
                                    }
                                    if (propertyDefinition.getRef() != null) {
                                        value = sigletons
                                                .get(propertyDefinition
                                                        .getRef());
                                    }
                                    if (propertyDefinition.getValue() != null) {
                                        value = propertyDefinition.getValue();
                                    }
                                    if (propertyDefinition.getLists() != null) {
                                        value = propertyDefinition.getLists();
                                    }
                                    if (propertyDefinition.getMaps() != null) {
                                        value = propertyDefinition.getMaps();
                                    }
                                    methodSetter.invoke(bean, value);
                                }
                                break;
                            }
                        }
                    }
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public Object getBean(String name) {
        return this.sigletons.get(name);
    }

}

public class test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        MySpringClassPathXmlApplicationContext1 ctx = new MySpringClassPathXmlApplicationContext1(
                "applicationContext.xml");
        PersonService personService = (PersonService) ctx
                .getBean("personService");
        personService.save();
    }

}

抱歉!评论已关闭.