Spring手写Spring框架解析XML文件并实例化Bean对象-----Spring框架

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.myspringframework</groupId>
    <artifactId>myspring</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
<!--            dom4j是一个可以解析XML文件的java组件,我们把他引入-->
            <groupId>org.dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>2.1.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.19.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j2-impl</artifactId>
            <version>2.19.0</version>
        </dependency>
        <!--JUNIT依赖-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>jaxen</groupId>
            <artifactId>jaxen</artifactId>
            <version>1.2.0</version>
        </dependency>
    </dependencies>
    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

</project>
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.myspringframework</groupId>
    <artifactId>myspring</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
<!--            dom4j是一个可以解析XML文件的java组件,我们把他引入-->
            <groupId>org.dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>2.1.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.19.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j2-impl</artifactId>
            <version>2.19.0</version>
        </dependency>
        <!--JUNIT依赖-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>jaxen</groupId>
            <artifactId>jaxen</artifactId>
            <version>1.2.0</version>
        </dependency>
    </dependencies>
    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

</project>
package org.myspringframework.core;

import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ClassPathXmlApplicationContext implements ApplicationContext
{
    private static final Logger logger = LoggerFactory.getLogger(ClassPathXmlApplicationContext.class);
    private Map<String,Object> singletonObjects = new HashMap<>();
    //解析mySpring配置文件,初始化所有的Bean,配置文件应当放在类路径下
    public ClassPathXmlApplicationContext(String configLocation)
    {
        try
        {
            //这是DOM4J解析XML的核心对象
            SAXReader saxReader = new SAXReader();
            //用类加载器获取系统类加载器,系统类加载器能获取类路径当中的资源,再以流的形式获取资源
            InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(configLocation);
            Document document = saxReader.read(in);
            //当XML文件有很多同名标签,如果需要获取就用//后加名字即可
            List<Node> list = document.selectNodes("//bean");
//            遍历Bean标签
            list.forEach(node -> {
                try
                {
                    //向下转型,方法更丰富
                    Element beanEle = (Element) node;
                    //获取ID
                    String id = beanEle.attributeValue("id");
                    //获取className
                    String className = beanEle.attributeValue("class");
                    logger.info(id + className);
                    //通过反射机制创建对象,将其放到Map集合中曝光
                    Class clazz = Class.forName(className);
                    Constructor constructor = clazz.getDeclaredConstructor();
                    //bean对象
                    Object o = constructor.newInstance();
                    singletonObjects.put(id,o);
                    logger.info(singletonObjects.toString());
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }

            });
            //解析XML文件,实例化Bean,把Bean放到map容器中
            //getBean方法就变成了调用get()方法,并传入一个key即Bean的ID即可
        }
        catch (DocumentException e)
        {
            e.printStackTrace();
        }
    }
    @Override
    public Object getBean(String name) {
        return singletonObjects.get(name);
    }
}
package org.myspringframework.core;

import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ClassPathXmlApplicationContext implements ApplicationContext
{
    private static final Logger logger = LoggerFactory.getLogger(ClassPathXmlApplicationContext.class);
    private Map<String,Object> singletonObjects = new HashMap<>();
    //解析mySpring配置文件,初始化所有的Bean,配置文件应当放在类路径下
    public ClassPathXmlApplicationContext(String configLocation)
    {
        try
        {
            //这是DOM4J解析XML的核心对象
            SAXReader saxReader = new SAXReader();
            //用类加载器获取系统类加载器,系统类加载器能获取类路径当中的资源,再以流的形式获取资源
            InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(configLocation);
            Document document = saxReader.read(in);
            //当XML文件有很多同名标签,如果需要获取就用//后加名字即可
            List<Node> list = document.selectNodes("//bean");
//            遍历Bean标签
            list.forEach(node -> {
                try
                {
                    //向下转型,方法更丰富
                    Element beanEle = (Element) node;
                    //获取ID
                    String id = beanEle.attributeValue("id");
                    //获取className
                    String className = beanEle.attributeValue("class");
                    logger.info(id + className);
                    //通过反射机制创建对象,将其放到Map集合中曝光
                    Class clazz = Class.forName(className);
                    Constructor constructor = clazz.getDeclaredConstructor();
                    //bean对象
                    Object o = constructor.newInstance();
                    singletonObjects.put(id,o);
                    logger.info(singletonObjects.toString());
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }

            });
            //解析XML文件,实例化Bean,把Bean放到map容器中
            //getBean方法就变成了调用get()方法,并传入一个key即Bean的ID即可
        }
        catch (DocumentException e)
        {
            e.printStackTrace();
        }
    }
    @Override
    public Object getBean(String name) {
        return singletonObjects.get(name);
    }
}

package org.myspringframework.core;

public interface ApplicationContext
{
    //根据Bean的名称获取对应的单例Bean对象
    Object getBean(String name);
}
package org.myspringframework.core;

public interface ApplicationContext
{
    //根据Bean的名称获取对应的单例Bean对象
    Object getBean(String name);
}
<?xml version="1.0" encoding="UTF-8"?>
<!--这个配置文件是mySpring开发人员提供的,使用者提供该文件-->
<beans>
    <bean id="user" class="com.powernode.myspring.bean.User">
        <property name="name" value="Jack"></property>
        <property name="age" value="30"></property>
    </bean>
    <bean id="userDaoBean" class="com.powernode.myspring.bean.UserDao">
    </bean>
    <bean id="userService" class="com.powernode.myspring.bean.UserService">
        <property name="userDao" ref="userDaoBean"></property>
    </bean>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<!--这个配置文件是mySpring开发人员提供的,使用者提供该文件-->
<beans>
    <bean id="user" class="com.powernode.myspring.bean.User">
        <property name="name" value="Jack"></property>
        <property name="age" value="30"></property>
    </bean>
    <bean id="userDaoBean" class="com.powernode.myspring.bean.UserDao">
    </bean>
    <bean id="userService" class="com.powernode.myspring.bean.UserService">
        <property name="userDao" ref="userDaoBean"></property>
    </bean>
</beans>
package com.powernode.myspring.bean;

public class UserService
{
    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void save()
    {
        userDao.insert();
    }
}
package com.powernode.myspring.bean;

public class UserService
{
    private UserDao userDao;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public void save()
    {
        userDao.insert();
    }
}
package com.powernode.myspring.bean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UserDao
{
    private static final Logger logger = LoggerFactory.getLogger(UserDao.class);
    public void insert()
    {
        logger.info("mysql数据库正在保存用户信息");
    }
}
package com.powernode.myspring.bean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class UserDao
{
    private static final Logger logger = LoggerFactory.getLogger(UserDao.class);
    public void insert()
    {
        logger.info("mysql数据库正在保存用户信息");
    }
}
package com.powernode.myspring.bean;

public class User
{
    private String name;
    private int age;

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

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

    public void setAge(int age) {
        this.age = age;
    }
}
package com.powernode.myspring.bean;

public class User
{
    private String name;
    private int age;

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

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

    public void setAge(int age) {
        this.age = age;
    }
}
package com.powernode.myspring.test;

import org.junit.Test;
import org.myspringframework.core.ApplicationContext;
import org.myspringframework.core.ClassPathXmlApplicationContext;

public class MySpringTest
{
    @Test
    public void Test()
    {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("myspring.xml");

    }
}
package com.powernode.myspring.test;

import org.junit.Test;
import org.myspringframework.core.ApplicationContext;
import org.myspringframework.core.ClassPathXmlApplicationContext;

public class MySpringTest
{
    @Test
    public void Test()
    {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("myspring.xml");

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
>