自己手动实现简单spring-ioc容器


自己手动实现简单spring-ioc容器





解析xml用的包


<dependency> <groupId>org.jdom</groupId> <artifactId>jdom2</artifactId> <version>2.0.5</version> </dependency>

 

public class Bean {
    //存类路径名
    private String className;
    //存对象
    private Map<String, Object> params;

    public Bean() {
    }

    public Bean(String className, Map<String, Object> params) {
        this.className = className;
        this.params = params;
    }

    public String getClassName() {
        return className;
    }

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

    public Map<String, Object> getParams() {
        return params;
    }

    public void setParams(Map<String, Object> params) {
        this.params = params;
    }

}

 

 测试的类
public class Student {
    private Integer id;
    private Integer age;
    private String name;
    public Student() {
    }

    public Integer getId() {
        return id;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

public class Teacher {
    private Integer id;
    private Integer age;
    private String name;
    public Teacher() {
    }

    public Integer getId() {
        return id;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

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

    @Override
    public String toString() {
        return "Teacher{" +
                "id=" + id +
                ", age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

 

测试xml

<beans>
    <bean id="Student" class="com.xiaocheng.Student">
        <property name="id" value="1"/>
        <property name="age" value="10"/>
        <property name="name" value="aaa"/>
    </bean>
    <bean id="Teacher" class="com.xiaocheng.Teacher">
        <property name="id" value="2"/>
        <property name="age" value="20"/>
        <property name="name" value="sss"/>
    </bean>
</beans>

 

 解析xml
public class FactoryBean {
    
    Map<String, Object> objectMap = new HashMap<>();

    public List<Element> getxml() throws Exception {
        //新建xml解析器
        SAXBuilder saxBuilder = new SAXBuilder();
        //使用绝对路径
        String path = "C:\\Users\\Administrator\\Documents\\myioc\\src\\main\\java\\resources\\applicationContext.xml";
        // 构造文档对象
        Document xmlDoc = saxBuilder.build(new FileInputStream(path));
        //获取根元素
        Element root = xmlDoc.getRootElement();
        //获取根元素下所有名字为bean的元素
        return root.getChildren("bean");
    }

    public List<Bean> getxmllist() throws Exception {

        List<Bean> beans = new ArrayList<>();

        for (Element e : getxml()) {
            //获取Element元素
            //获取id属性的值
            String id = e.getAttributeValue("id");
            //获取property的class属性的值
            String classname = e.getAttributeValue("class");

            System.out.println(" id: " + id + " class: " + classname);

            Class<?> clazz = Class.forName(classname);

            //遍历bean下的所有properyt属性,并调用setter方法,将值注入给对应的属性
            if (e.getChild("property") != null) {
                Map<String, Object> map = new HashMap<>();
                for (Element p : e.getChildren("property")) {
                    Integer valuetemp=null;
                    String name = p.getAttributeValue("name");
                    String value = p.getAttributeValue("value");

                    Field[] fields = clazz.getDeclaredFields();

                    for (Field field : fields) {
                        if (name.equals(field.getName())) {
                            String type = split(field.getType().toString(), "\\.");
                            if ("Integer".equals(type)) {
                                valuetemp = Integer.valueOf(value);
                            }
                            //如需更多类型增加判断变量
                        }
                    }
//                    System.out.println(name + "=" + value);
                    if (valuetemp!=null) {
                        map.put(name, valuetemp);
                    }else {
                        map.put(name, value);
                    }
                }
                Bean bean = new Bean(classname, map);
                beans.add(bean);
            }
        }
        return beans;
    }

public String split(String str, String separator) { //取到最后一段字符串 return str.split(separator)[str.split(separator).length - 1]; } public Map<String, Object> creatBeans() throws Exception { for (Bean item : getxmllist()) { String className = item.getClassName(); Map<String, Object> params = item.getParams(); Object object = createBean(className, params); objectMap.put(split(className, "\\."), object); } // /**返回对象的map*/ return objectMap; } /** * 创建Bean对象 * * @param className:类的全路径 * @param params:成员变量的名和值 */ private Object createBean(String className, Map<String, Object> params) throws Exception { Class<?> clazz = Class.forName(className); /*创建对象*/ Object object = clazz.newInstance(); // /**获取对象中的变量和value*/ Set<Map.Entry<String, Object>> entries = params.entrySet(); for (Map.Entry<String, Object> entry : entries) { // /**获取成员变量名称*/ String paramName = entry.getKey(); Method method = createMethod(clazz, paramName); // /*invoke():函数调用*/ method.invoke(object, entry.getValue()); } return object; } /** * @param clazz:类的class对象 * @param name:成员变量名称 */ private Method createMethod(Class<?> clazz, String name) throws Exception { //拼接函数名称 StringBuilder methodName = new StringBuilder("set").append(name.substring(0, 1).toUpperCase()).append(name.substring(1)); Method method = null; // /**获取所有的成员函数*/ Method[] methods = clazz.getMethods(); ///**methodName:获取函数名称, getParameterTypes():获取函数的参数列表*/ for (Method m : methods) { if (m.getName().equals(methodName.toString())) { // /**methodName:获取函数名称, getParameterTypes():获取函数的参数列表*/ method = clazz.getMethod(methodName.toString(), m.getParameterTypes()); break; } } return method; } public static void main(String[] args) throws Exception { FactoryBean factoryBean = new FactoryBean(); Map<String, Object> objectMap = factoryBean.creatBeans(); Teacher teacher = (Teacher) objectMap.get("Teacher"); Student student = (Student) objectMap.get("Student"); System.out.println(teacher.toString()); System.out.println(student.toString()); } }

 

posted @ 2022-02-17 19:58  依笑  阅读(100)  评论(0编辑  收藏  举报