package com.freewebsys.sns.common; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.Enumeration; import java.util.Iterator; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.dom4j.Document; import org.dom4j.DocumentFactory; import org.dom4j.Element; import org.dom4j.io.SAXReader; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; public class SysConfUtil { /** * @param args * @throws MalformedURLException */ public static void main(String[] args) throws MalformedURLException { // TODO Auto-generated method stub System.out.println(getConfigValue("mail.host")); // System.out.println(getConfigValue("mail.username")); } private static Document document = null; static { Enumeration<URL> xmls; SAXReader reader = new SAXReader(DocumentFactory.getInstance()); try { xmls = Thread.currentThread().getContextClassLoader() .getResources("META-INF/persistence.xml"); if (xmls.hasMoreElements()) { URL configURL = xmls.nextElement(); document = reader.read(configURL.openStream()); } } catch (Exception e) { System.out.println("加载配置失败:" + e.getMessage()); } // System.out.println(document.selectSingleNode("@name=mail.host")); } @SuppressWarnings("unchecked") public static String getConfigValue(String name) { System.out.println(document.getRootElement().getName()); // /*[name()='persistence']/*[name()='persistence-unit']/*[name()='properties']/*[name()='property'] // 得到根节点 Element root = document.getRootElement(); // 得到persistenceUnit Element persistenceUnit = root.element("persistence-unit"); // 得到下面的属性 Element properties = persistenceUnit.element("properties"); // 对属性进行循环,找到自定义的配置 for (Iterator<Element> i = properties.elementIterator("property"); i .hasNext();) { Element property = i.next(); if (property.attributeValue("name") != null && property.attributeValue("name").equals(name)) { // 如果有这个属性返回value return property.attributeValue("value"); } } return ""; } }
经过 测试 可以读取 配置文件.并且 打成 jar 包之后 也可以读取到配置文件.
在 properties 下面添加 自己的属性就 property
就可以读取了..比如我添加了. 邮件的配置.