手动开发- 简单的 Spring 基于 XML 配置的程序

思路

  • 利用dom4j 读取 beans.xml配置文件
  • 获取到文件中配置的实体类全路径,通过反射生成对象
  • 将该对象放入 ConcurrentHashMap容器中,并提供一个getBean方法,可以通过id获取到该对象

代码

import org.dom4j.Document;  
import org.dom4j.DocumentException;  
import org.dom4j.Element;  
import org.dom4j.io.SAXReader;  
  
import java.io.File;  
import java.util.List;  
import java.util.concurrent.ConcurrentHashMap;  
  
public class ApplicationContext {  
   private ConcurrentHashMap<String, Object> singletonObjects =  
            new ConcurrentHashMap<>();  
  
   //构造器  
    // 接收一个容器的配置文件, 比如 beans.xml, 该文件默认在src  
    public ApplicationContext(String iocBeanXmlFile) throws Exception {  
  
        //1. 得到类加载路径  
        String path = this.getClass().getResource("/").getPath();  
  
        //2. 创建 Sareader        SAXReader saxReader = new SAXReader();  
  
        //3. 得到Document对象  
        Document document = saxReader.read(new File(path + iocBeanXmlFile));  
          
        //4 得到rootDocument  
        Element rootElement = document.getRootElement();  
          
        //5 得到第一个bean-monster01的相关属性  
        Element bean = (Element)rootElement.elements("bean").get(0);  
          
        //6. 获取到第一个bean-monster01的相关属性  
        String id = bean.attributeValue("id");  
        String classFullPath = bean.attributeValue("class");  
        List<Element> property = bean.elements("property");  
  
        // 遍历  
        Integer monsterId = Integer.parseInt(property.get(0).attributeValue("value"));  
  
        String name = property.get(1).attributeValue("value");  
        String skill = property.get(2).attributeValue("value");  
  
        //7. 使用反射创建对象 => 回顾反射机制  
        Class<?> aClass = Class.forName(classFullPath);  
        // 这里O对象就是Monster对象  
        Monster o = (Monster)aClass.newInstance();  
  
        o.setMonsterId(monsterId);  
        o.setName(name);  
        o.setSkill(skill);  
  
        //8 将创建好的对象放入到singletonObjects  
        singletonObjects.put(id,o);  
  
    }  
  
    public Object getBean(String id) {  
        return singletonObjects.get(id);  
    }  
}

测试

   
public class ApplicationContextTest {  
    public static void main(String[] args) throws Exception {  
        ApplicationContext ioc = new ApplicationContext("beans.xml");  
  
        Monster monster01 = (Monster)ioc.getBean("monster01");  
  
        System.out.println("monster01=" + monster01);  
        System.out.println("monster01.name=" + monster01.getName());  
        System.out.println("ok");  
  
    }  
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值