栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

[黄昏]借助jdom解析xml模拟spring的getbean功能

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

[黄昏]借助jdom解析xml模拟spring的getbean功能

1.beans.xml


 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:tx="http://www.springframework.org/schema/tx"
   xmlns:aop="http://www.springframework.org/schema/aop" 
   xsi:schemaLocation="
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
">
   
 
 
   
       
       
   

2.创建pojo类student


package testspring.bean;


public class Student {
    private int id = 1;
    private String name  = "张三";
    private String clazz = "大四一班";
    
    public int getId() {
        return id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public String getClazz() {
        return clazz;
    }
    
    public void setClazz(String clazz) {
        this.clazz = clazz;
    }   

}
3.利用jdom模拟spring的getbean功能

//解析xml文件,获取相关节点的属性,并通过反射实例化


package springReadBeanTest;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.jdom.document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import testspring.bean.Student;


public class JdomParseXmlSpringGetBean {

    
    public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, JDOMException, IOException {
    
        // 获取SAX解析器
        SAXBuilder builder = new SAXBuilder();
        File file = new File("src/springReadBeanTest/Beans.xml");
        // 获取文档
        document doc = builder.build(new File(file.getAbsolutePath()));
        // 获取根节点
        Element root = doc.getRootElement();
        System.out.println(root.getName());
        // 获取根节点下所有的子节点, 也可以根据标签名称获取指定的直接点
        List list = root.getChildren();
        System.out.println(list.size());
        for(int x = 0; x

        Element e = list.get(x);
        if(e.getName().contentEquals("bean")){
            String aString = e.getAttribute("class").getValue();
            Student student = (Student) Class.forName(aString).newInstance();
            System.err.println(student.getName());
            break;
        }
        
        
       

    }
    }
}
 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/712344.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号