java讀取配置節點config字尾名檔案
阿新 • • 發佈:2019-02-20
以前都是讀取properties檔案,現在過來分享一下讀取config檔案
1.新建WebSiteConfig.java
private String UserName="192.168.2.204:11211"; private String password ="": //set get省略
2.新建中介軟體工具類CenterUtils.java
import java.beans.IntrospectionException; import org.xml.sax.SAXException; private static WebSiteConfig _WebSiteCfg; // 網站配置 public static WebSiteConfig GetWebSiteConfig() { try { if (_WebSiteCfg == null) { _WebSiteCfg = (WebSiteConfig) XMLUtil.xmlFile2Bean( WebSiteConfig.class, Constanst.WEBROOTPATH + Constanst.WEBSITECONFIGPATH, "UTF-8"); } } catch (IOException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IntrospectionException e) { e.printStackTrace(); } return _WebSiteCfg; }
3.新建常量類Constanst
//配置檔案地址 該路徑是WebRoot/XConfig/jdbc.config
public static final String WEBSITECONFIGPATH = "/XConfig/jdbc.config"; public static final String WEBROOTPATH = Constanst.class .getProtectionDomain().getCodeSource().getLocation().getPath() .indexOf("WEB-INF") > 0 ? Constanst.class .getProtectionDomain() .getCodeSource() .getLocation() .getPath() .substring( 0, Constanst.class.getProtectionDomain().getCodeSource() .getLocation().getPath().indexOf("WEB-INF/classes")) : Constanst.class.getProtectionDomain().getCodeSource() .getLocation().getPath();
4.測試
System.out.println(CenterUtils.GetWebSiteConfig().getUsername());//root 這裡會根據jdbc.config配置節點的值,並不是類的192.168.2.204:11211";
System.out.println(CenterUtils.GetWebSiteConfig().getPassword())//1234
5配置檔案jdbc.config
<?xml version="1.0" encoding="UTF-8"?> <WebSiteConfig> <username>root</username> <password>1234</password> </WebSiteConfig>
6.這中間有個jar包 XMLUtil需要
所需jar