如何加载xml配置文件和proprieties

来源:互联网 发布:javascript 加载顺序 编辑:程序博客网 时间:2024/05/21 18:10
                            xml
运用dom4j
                Document document = getInstance("src/myObject.xml");
//得到根元素
Element root = document.getRootElement();
//得到第一个元素action
Element element = root.element("action");
//得到第一个元素的属性
String name=element.attributeValue("class");
System.out.println(name);

   properties
 //加载配置文件
InputStream in=new FileInputStream("src/dbconfig.properties");
/*第二种方式 加载配置文件*/
/*InputStream in = JdbcUtil.class.getClassLoader()
.getResourceAsStream("dbconfig.properties");*/
Properties props=new Properties();
props.load(in);
String username=props.getProperty("username");






扩展struts2执行过程


    从请求路径中得到要的路径,到src中去找配置struts.xml 中name为路径,用到dom4j取解析xml 然后得到包的路径 通过反射 带到类的对象


           Document document = getInstance("src/myObject.xml");
//得到根元素
Element root = document.getRootElement();
//得到第一个元素action
Element element = root.element("action");
//得到第一个元素的属性
String name=element.attributeValue("class");
System.out.println(name);

//运用反射的获取User对象
Class clazz=Class.forName(name);
/*//第一种方式  
        //Method getMethod("add", new Class[]{int.class, int.class});
        
        //Object invoke(invokeTester, new Object[]{new Integer(100), new Integer(200)});
User user=(User) clazz.newInstance();
   Method method = clazz.getMethod("show");
   method.invoke(user);*/
   //第二种方式
//得到实例对象
User user=(User) clazz.newInstance();
user.show();
    
    
原创粉丝点击